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

Server side rendering + react router redirect

本文关键字:路由器 重定向 服务器端      更新时间:2023-09-26

我有一个更高阶的组件(由下面的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="

我在这里做错了什么?

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

摘自这些React文档:

Node.js的某些版本具有不保留密钥顺序的Object.assign实现。这可能会在验证标记时导致错误,从而创建一个警告,上面写着"React试图重用容器中的标记,但校验和无效"。如果遇到此问题,可以覆盖Object.assign以使用保留键顺序的polyfill。

安装对象分配包并按如下方式设置全局Object.assign可能会解决您的问题:

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

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