4

我需要使用 react-router 从服务器端的另一个页面重定向页面。我编写的代码在客户端工作,但不在服务器渲染中。你可以在这里找到代码:

https://github.com/jurgob/iso-login/blob/e26af0152896a949435db62549027b2683276db7/src/shared/components/LoginPage.js

这是/src/shared/components/LoginPage.js内的重定向代码:

componentWillMount() {
    ...
    this.props.history.replaceState(null, '/home');
  }

笔记:

如果您查看https://github.com/jurgob/iso-login/blob/e26af0152896a949435db62549027b2683276db7/src/shared/routes.js

我做了:

function requireAuth(nextState, replaceState) {
  // replaceState({ nextPathname: nextState.location.pathname }, '/login');
}
...
<Route path="home" component={HomePage} onEnter={requireAuth} />

此代码有效,但我想在组件内进行重定向

4

2 回答 2

2

React Router 中没有内置功能来处理服务器端组件内的重定向。

这是因为onEnterhooks 在 的上下文中运行match,所以 React Router 可以接听replaceState调用并通知match回调请求的转换。通过时间componentWillMount运行,match已经调用了回调。

您很可能必须构建一些更高级别的抽象,以便在服务器上渲染时检测调用,然后在返回history.replaceState后采取适当的操作。ReactDOM.renderToString

于 2015-10-26T04:17:53.180 回答
1

处理此问题的几种不同方法:

1 - 如果您可以让重定向实际发生在客户端,您可以执行类似的操作

history.push('/newPath/');

这是我使用的解决方案,以便没有两种不同类型的重定向(在客户端和服务器上)。就我而言,我传入了一个“上下文”道具(仅适用于代码的服务器端部分,所以我的方法看起来更像

componentWillMount() {
  if (this.props.context) { // context only available on server side
    this.props.context.doLogout();
  }
  this.props.history.push('/newPath/');
}

2 - 如果您真的希望服务器进行重定向,那么您必须从 express 或您使用的任何框架传递响应对象:

componentWillMount() {
  // you may have to this.props.history.push('/currentPath');
  this.props.res.redirect(302, '/newPath/');
}

如有必要,很高兴详细说明 - 我花了一些时间来解决这个问题,并选择了前一种解决方案(代码简单而不是正确性,但不管对你有用)。

于 2015-12-22T02:34:29.240 回答