我有一个React / Redux应用程序,可以跟踪用户在本地存储中的身份验证状态.该应用程序也设置为使用服务器端呈现.我在渲染初始应用程序状态时遇到了问题.我的服务器创建一个新商店并
由于此时服务器和客户端不同步,我收到此错误:
React attempted to reuse markup in a container but the checksum was invalid. This generally means that you are using server rendering and the markup generated on the server was not what the client was expecting. React injected new markup to compensate which works but you have lost many of the benefits of server rendering. Instead, figure out why the markup being generated is different on the client or server:
这是有道理的,因为服务器正在尝试呈现未经身份验证的状态.
设置此初始状态的公认标准或惯例是什么,该状态仅依赖于客户可以访问的内容?
我发现OP是对的,cookie存储是最好的选择.如果您使用react,redux和express为通用应用程序,那么对我有用的选项是 https://github.com/eXon/react-cookie.实质上:
在您的服务器端代码中,您可以使用:
import cookie from 'react-cookie'; function handleRender(req, res) { cookie.setRawCookie(req.headers.cookie); // Create new Redux store instance const store = createStore(rootReducer, { username: cookie.load('username') || '', accessLevel: cookie.load('accessLevel') || userRoles.public, }); //other react/redux/express related code }
在您的react应用程序中,在组件内部,您可以直接保存cookie:
import cookie from 'react-cookie'; //first parameter is anything you want, second is the data you want to save cookie.save( 'username', username ); cookie.save('accessLevel', accessLevel);
此外,如果你想存储一个对象,就像我一样,你可以传入JSON.stringify(你的对象). cookie.load会自动为你解析它.
在我的代码中,我从操作中调用了cookie.save,但您可以直接在组件或任何抽象中调用它.