Pat*_*nik 7 reactjs server-side-rendering next.js
我有这样的js代码:
let idCounter = 0;
export default class TestComponent extends Component {
constructor(props) {
super(props);
this.uniqueId = `TestComponent-${idCounter++}`;
}
render() {
return (<div id={this.uniqueId> Some content </div>);
}
}
Run Code Online (Sandbox Code Playgroud)
我需要为每个渲染元素拥有唯一的 ID,所以我对它们进行计数。但我有 Next.js 的 SSR。当页面在服务器上初始化时,由于服务器渲染,idCounter 会增加几次。
然后普通浏览器尝试渲染此组件,从 idCounter 从 0 开始并替换服务器端渲染的 id(例如“TestComponent-5”到“TestComponent-0”)。我最终在控制台中出现错误:
“警告:Prop
id不匹配。服务器:“TestComponent-5”客户端:“TestComponent-0””
我不知道该怎么处理。有任何想法吗?
小智 6
我发现这个问题已经很老了,但无论如何,我一整天都在努力解决这个问题,直到找到解决方案。而且相关信息似乎并不多。
有一个名为react-uid 的库,它对SSR 友好。您只需将应用程序包装在 UIDReset 中,并在组件中使用 UIDConsumer 提供的唯一 ID
/pages/index.tsx:
import { UIDConsumer } from 'react-uid'
...
const Index = () => {
return (
<>
<UIDReset prefix="uid_">
<Layout>
<Head>
<title>Next.js App</title>
</Head>
<MyComponent />
</Layout>
</UIDReset>
</>
)
Run Code Online (Sandbox Code Playgroud)
/组件/MyComponent.tsx
import { UIDConsumer } from 'react-uid'
...
return(
<UIDConsumer>
{(id) => (
(<div id={id}> Some content </div>);
)}
</UIDConsumer>
)
Run Code Online (Sandbox Code Playgroud)
希望仍然会有帮助。
| 归档时间: |
|
| 查看次数: |
4111 次 |
| 最近记录: |