【问题标题】:Next.js update state depending on router.asPathNext.js 更新状态取决于 router.asPath
【发布时间】:2021-11-12 21:47:11
【问题描述】:

我有一个带有步进器的 next.js 多步表单。步进器在初始加载时具有以下状态:

  const [steps, setStepsData] = useState([
    { name: 'Vertrag', status: 'current' },
    { name: 'Dateneingabe', status: 'upcoming' },
    { name: 'Bestätigung', status: 'upcoming' },
  ]);

这种状态是在上下文中处理的,我还使用Router 根据表单步骤设置我的 URL。每次用户单击下一步按钮时,都会调用以下函数:

  const nextFormStep = (contract='') => {
    const nextStep = formStep + 1;
    router.push(`?step=${nextStep}`);
    setFormValues({ contract });
  };

到目前为止一切顺利。现在在我的上下文中,我想检查 router.asPath === '/?step=1' 是否应该像这样:

router.asPath === '/?step=1' ? setStepsData( steps => [
  { name: 'Vertrag', status: 'current' },
  { name: 'Dateneingabe', status: 'current' },
  { name: 'Bestätigung', status: 'upcoming' },]) : console.log('doesnt work')
}, [])

所以,如果我就这样离开它,我会得到一个 错误:重新渲染太多。 React 限制了渲染的数量以防止无限循环。 我想,我可能需要像这样使用 useEffect:

useEffect(() => { 
      router.asPath === '/?step=1' ? setStepsData( steps => [
      { name: 'Vertrag', status: 'current' },
      { name: 'Dateneingabe', status: 'current' },
      { name: 'Bestätigung', status: 'upcoming' },]) : console.log('doesnt work') 
}, [])

只有在我点击浏览器中的重新加载按钮后,这种方法状态才会发生变化,而不是 更改为下一个表单步骤。如何达到以下行为:我点击下一步按钮 - url 路径更改,状态更改,我再次点击返回按钮,url 更改,步骤状态也是如此?

【问题讨论】:

  • 尝试在依赖数组中传递路由器

标签: reactjs next.js next-router


【解决方案1】:

我只需要“订阅”路由器的更改,如下所示:

router.asPath === '/?step=1' ? setStepsData( steps => [
  { name: 'Vertrag', status: 'current' },
  { name: 'Dateneingabe', status: 'current' },
  { name: 'Bestätigung', status: 'upcoming' },]) : console.log('doesnt work')
}, [router])

从上面的评论和这个 SO-post 中得到提示:useEffect doesn't update state on route change

【讨论】:

    猜你喜欢
    • 2020-03-03
    • 1970-01-01
    • 2013-10-30
    • 1970-01-01
    • 2019-05-20
    • 2013-05-27
    • 2021-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多