如何让 React 补液忽略特定组件的校验和?

How to let React rehydration ignore checksums of specific components?

重新水化时,如果最初呈现的标记与服务器标记完全不匹配,React 会报错。然而,某些组件在客户端和服务器端产生不同结果的情况并不少见。最简单的,考虑一个显示当前时间的组件:

function Now() {
  return <span>{ new Date().toString() }</span>;
}

显然,这样的组件在每次渲染时都会显示不同的值,因此 React 将始终警告不正确的校验和。

如果客户端针对特定组件呈现与服务器不同的内容,我如何告诉 React 没问题?

回答我自己的问题,因为 React v16 the documentation 是这样说的:

If you intentionally need to render something different on the server and the client, you can do a two-pass rendering. Components that render something different on the client can read a state variable like this.state.isClient, which you can set to true in componentDidMount(). This way the initial render pass will render the same content as the server, avoiding mismatches, but an additional pass will happen synchronously right after hydration. Note that this approach will make your components slower because they have to render twice, so use it with caution.