简体   繁体   English

为什么 router.push 使用 next.js 重新加载/重新渲染页面?

[英]Why does router.push reload / re-render the pages with next.js?

In my component, I have:在我的组件中,我有:

    return (
        <TouchableRipple onPress={() => router.push(`/conversations/${props.item.id}`)} style={{ marginBottom: 50 }}>
            <Surface style={{ height: 200, flex: 1, flexDirection: 'row', justifyContent: 'flex-start', borderRadius: customTheme.roundness, elevation: customTheme.elevation }}>

It goes to /conversations/1 , but rerenders the entire page.它转到/conversations/1 ,但会重新呈现整个页面。 Am I missing something?我错过了什么吗?

You need to provide 2 parameters to the push for it not to reload:您需要为推送提供 2 个参数以使其不重新加载:

router.push(
  `/conversations/query-param=${props.item.id}`,
  `/conversations/${props.item.id}`
)

The query-param is the named parameter used in conversations query-param是对话中使用的命名参数

if you are using getInitialProps inside your conversations page, then it will refresh the page for you you need to use https://github.com/fridays/next-routes如果您在对话页面中使用 getInitialProps,那么它将为您刷新页面,您需要使用https://github.com/fridays/next-routes

I think the issue lies with the next router giving a new instance on every change.我认为问题在于下一个路由器在每次更改时都会提供一个新实例。 You probably have the following code:您可能有以下代码:

const myPage = (props) => {
  const router = useRouter();
  
  return (...);

Essentially you are changing the router object as router.query now contains the updated url params.本质上,您正在更改路由器 object,因为 router.query 现在包含更新的 url 参数。 It seems that the router will give back a completely new instance of the router.似乎路由器将返回一个全新的路由器实例。 Hence your functional component is updated because one of it's external dependencies changed.因此,您的功能组件已更新,因为它的外部依赖项之一已更改。 I too am looking for a solution to stop that behavior.我也在寻找一种解决方案来阻止这种行为。

Quick fix: Move the expensive computations to a component and call that from your page.快速修复:将昂贵的计算转移到一个组件并从您的页面调用它。 Then on your page add a quick cache to query (such as const routerPush = useMemo(() => router.push, []); and pass that into the component.然后在您的页面上添加一个快速缓存以进行查询(例如const routerPush = useMemo(() => router.push, []);并将其传递给组件。

Did you try with brackets instead?你试过用括号代替吗?

<TouchableRipple onPress={() => router.push(`/conversations/[props.item.id]`)} style={{ marginBottom: 50 }}>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM