【问题标题】:Nextjs mix SSR and client data in componentsNextjs 在组件中混合 SSR 和客户端数据
【发布时间】:2020-05-29 09:51:11
【问题描述】:

我遇到的情况是,当涉及随机化时,同一组件显示混合数据,html 部分来自 SSR 和部分来自客户端渲染的混乱数据。

代码如下:

const Component = (props) => {
    const rand = Math.random();
    console.log('==========================', rand);

    return <a href={rand}>{rand}</a>
}

结果如下。

SSR:

========================== 0.30408232064749563

客户端渲染:

========================== 0.6842738761932372

结果 HTML:

<a href="0.30408232064749563">0.6842738761932372</a>

所以a 标记在href 中获取旧的SSR 值,而文本值得到更新。

【问题讨论】:

  • 如你所见,React 假设来自服务器和客户端的渲染组件匹配。我建议在 useEffect 挂钩中执行 rand,该挂钩仅在客户端中运行。
  • 我可以使用任何类型的 isServer 检查并仅在客户端进行,但这并不能解决我的问题。用户案例要求在这两种情况下随机分配一些内容。
  • 您可以尝试使用useRef 存储Math.random。服务器端和客户端应该是一样的。
  • 您可以尝试使用具有相同值的key
  • 没有任何帮助,似乎问题只存在于生产模式中

标签: reactjs random next.js


【解决方案1】:

如果要使SSR和CSR中的数据相同,则应在getInitialProps中创建Math.random()并通过props传递。

const Component = props => {
  console.log(props.rand)
}

Component.getInitialProps = async () => {
  const rand = Math.random();
  console.log(rand);

  return {
    rand
  }
}

【讨论】:

    猜你喜欢
    • 2022-08-10
    • 2021-05-12
    • 2022-12-25
    • 2021-10-28
    • 2022-11-02
    • 1970-01-01
    • 2015-06-06
    • 1970-01-01
    • 2020-11-06
    相关资源
    最近更新 更多