【发布时间】:2020-11-18 10:30:11
【问题描述】:
我正在使用 React/Next 构建一个无头电子商务网站,并有一个用于生成所有产品页面的 [product].js 动态路由,使用 getStaticPaths() 和 getStaticProps() 生成页面正常。
我在[product].js 中使用useState 挂钩来管理数字输入(用于数量)和其他一些事情。
加载的第一个产品页面工作正常,但是当我转到其他产品页面时,它们使用与第一个产品相同的状态。
有没有办法让状态在路由更改之间不存在?
通过一些挖掘,我发现这是 next 的问题,并且在他们的积压中。它本质上源于组件没有密钥的事实。这意味着在同一动态路由上的路由之间切换不会正确注册并导致组件使用陈旧状态。
我找到的一个可能的解决方案是:
export async function getStaticProps({params}) {
const props = await getData(params);
// key is needed here
props.key = data.id;
return {
props: props
}
}
这是我的实现,对我不起作用:
export default function ProductPage(props) {
// this state doesn't reset between dynaic route changes
const [quantity, setQuantity] = useState(1)
return(
...
)
}
export async function getStaticProps({ params }) {
const slug = params.product
const props = await client.query({
query: singleProductQuery,
variables: { id: slug }
})
props.key = props.data.product.slug
return {
props: props
}
}
我尝试将内容包装在另一个组件中并为其添加一个键,如下所示:
return(
<OuterComponent key={props.id}>
// components within here, that have their own state, now work
</OuterComponent>
)
由于这个新的keyed组件只是在return语句中,并没有封装状态钩子,所以不起作用。但是,对于在包装组件中找到的任何组件,这确实会重置状态。
【问题讨论】:
标签: javascript reactjs react-hooks next.js