gpt4 book ai didi

reactjs - 使用nextjs切换页面时如何只更改一个组件?

转载 作者:行者123 更新时间:2023-12-03 17:29:21 24 4
gpt4 key购买 nike

背景

我想构建一个网页,每当我将 url 更改为另一个路径时,它都不会触发导航,我的意思是,它不会再次加载页面;相反,我希望此 url 更改更改页面中一个组件“x”的属性。根据url路径,会导致组件“x”加载不同的属性;

代码示例

在下面的示例中,根据单击的链接,它会在空段落行上显示不同的值:如果 url 路径只是“/”,它应该是空的,但是如果我单击链接 1,它应该显示“value1”,如果我点击链接 2,它应该显示“value2”。在这两种情况下,我都不想触发导航,我只想更改 url 并且段落上的值也相应地更改。

import React from 'react'
import Link from 'next/Link'


const example = ()=>{
return(
<div>
<div>
<h1>Example</h1>
<Link href='/value1'><a>Link 1</a></Link>
<Link href='/value2'><a>Link 2</a></Link>
</div>
<div>
<p> Value <p>
</div>
</div>
)
}

export default example

问题

我怎样才能使用 NextJS 做到这一点?我知道有浅层路由,但根据我在这个问题上的发现 https://github.com/zeit/next.js/issues/3253没有特定的方法可以做到这一点......
我知道可以使用 react-router 来完成,但是为了学习 nextJS,我想知道如何使用这个工具来做这样的事情。

感谢您的任何帮助!

最佳答案

使用 Next.js Shallow Routing .

Shallow routing allows you to change the URL without running data fetching methods again, that includes getServerSideProps, getStaticProps, and getInitialProps.

You'll receive the updated pathname and the query via the router object (added by useRouter or withRouter), without losing state.

To enable shallow routing, set the shallow option to true.



应用于您的示例:
// pages/[index].js

import { useEffect } from 'react'
import { useRouter } from 'next/router'

export default function Index() {
const router = useRouter()

return (
<>
<a onClick={() => router.push('/?value=1', undefined, { shallow: true })}>
Value 1
</a>

<a onClick={() => router.push('/?value=2', undefined, { shallow: true })}>
Value 2
</a>

<p> {router.query.value} <p>
</>
)
}

关于reactjs - 使用nextjs切换页面时如何只更改一个组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57558801/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com