英文:
Router.refresh() not refreshing in next 13?
问题
代码似乎直接跳过了 refresh()
函数,但其余的 API 调用工作正常。有人知道为什么无法刷新吗?
英文:
'use client';
import { useRouter } from "next/navigation";
export default function Todo({ todo }) {
const router = useRouter();
return (
<>
<li key={todo.id}>
<input type='checkbox' checked={todo.isDone} onChange={(e) => update(todo.id, e.target.checked, router.refresh)}></input>
{todo.name}
<button onClick={() => todoDelete(todo.id, router)}>Delete</button>
</li>
</>
)
async function todoDelete(id, router) {
await fetch(`/api/todo/delete?id=${id}`, {
method: 'DELETE',
});
router.refresh();
}
}
The code seems to jump right over the refresh() function, but the rest of the API call is working fine. Anyone know why I'm unable to refresh?
答案1
得分: 1
router.refresh()
用于服务器渲染的组件。它通过在服务器上重新渲染组件并发送带有更新数据的新版本来工作 - 因此它不适用于客户端组件,因为服务器上没有渲染任何内容(这是因为顶部有'使用客户端'指令)。
来自Next 13 App Router beta文档链接:
在数据变异后,您可以使用
router.refresh()
来刷新(获取更新的数据并在服务器上重新渲染)从根布局到当前路由的内容。
如果要在客户端端处理变异,您必须自行管理状态并重新获取数据。
英文:
router.refresh()
is meant for server-rendered components. It works by re-rendering the component on the server and sending back a fresh version with the updated data - thus it doesn't work on client-facing components because there is nothing rendered on the server (which is what you have here because of the 'use client' directive at the top)
From the Next 13 App Router beta docs:
> After a data mutation, you can use router.refresh() to refresh (fetch updated data and re-render on the server) the current route from the root layout down.
If you want to handle mutation on the client side, you have to manage the state and re-fetch the data yourself.
答案2
得分: 0
@adham. useRouter 是 React Hook,只能在客户端使用。
useRouter.refresh 可以在 https://nextjs.org/docs/app/api-reference/functions/use-router 找到。
你可能正在谈论来自 "next/router" 的 useRouter,但它在 next13 中不可用。
英文:
@adham. useRouter is react hook and can only be called on the client side
useRouter.refresh is https://nextjs.org/docs/app/api-reference/functions/use-router.
You're probably talking about useRouter from "next/router" which is not available in next13
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论