服务器端渲染+反应路由器重定向

时间:2016-05-06 20:16:06

标签: javascript reactjs react-router redux isomorphic-javascript

我有一个更高阶的组件(由下面的wrapAuthComponent应用),它包装了任何需要身份验证的组件。此组件检查用户是否已登录,如果没有,则重定向:

let next = this.props.location.pathname;
this.context.router.push({
    pathname: '/login',
    query: {...this.props.location.query, next}
});

另外,我有一个导航栏组件,允许用户登录:

<IndexLinkContainer to={`/login? next=${this.props.pathname}`}>
    <NavItem className='nav-bar-button'> Login </NavItem>
</IndexLinkContainer>

(上面的pathname道具由App容器传递)

所以,回顾一下,我的路线是这样绘制的:

<Route component={App} /* app contains the above navbar */ path="/">
    <Route component={LoginPage} path="/login" />
    <Route component={wrapAuthComponent(Foo)} path="/foo" />
</Route>

现在,关于bug。 当我转到/foo但未登录时,我收到以下错误:

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:
 (client)  href="/login?next=/login" data-reactid=
 (server)  href="/login?next=/foo" data-reactid="

我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

根据您的Node.js和React版本,this GitHub issue可能与您的问题有关。

取自these React docs:

  

某些版本的Node.js具有Object.assign实现,该实现不保留键顺序。这可能会在验证标记时导致错误,并创建一条警告,显示“React尝试在容器中重用标记,但校验和无效”。如果遇到此问题,可以覆盖Object.assign以使用保留键顺序的polyfill。

安装object-assign软件包并按如下方式设置全局Object.assign可能会解决您的问题:

Object.assign = require('object-assign');

如果没有,我认为在确定问题之前我需要查看更多代码。

相关问题