Router.refresh() 在接下来的13个周期内没有刷新?

huangapple go评论70阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年3月7日 03:26:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/75655010.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定