Nextjs将SSR和客户端数据混合在组件中

问题描述 投票:0回答:1

我面对的情况是,当涉及随机化时,同一组件显示混合数据时,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值,而文本值得到了更新。

reactjs random next.js
1个回答
0
投票

如果要在SSR和CSR中使数据相同,则应在Math.random()中创建getInitialProps,然后将其传递给props

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

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

  return {
    rand
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.