gpt4 book ai didi

react-router - 在 onEnter 中使用 replaceState 时 this.props.location.state 为 null

转载 作者:行者123 更新时间:2023-12-04 04:54:55 24 4
gpt4 key购买 nike

我一直在关注 react-router 1.0.3 的 auth-flow 示例:

var requireAuth = function(nextState, replaceState){
if(!auth.loggedIn()){
replaceState({ nextPathname: nextState.location.pathname }, '/login');
}
}

export default (
<Route component={App}>
<Route path='/login' component={Login}/>
<Route path='/' component={Messenger} onEnter={requireAuth}/>
</Route>
);

当某人未登录时,函数 replaceState 会按预期执行,显示/login 页面,但状态:
{ nextPathname: nextState.location.pathname }
应该在 this.props.location.state 中找不到。相反 this.props.location.state 是未定义的。

这似乎与以下问题相同:
https://github.com/rackt/react-router/issues/2768

有人知道为什么没有设置状态吗?

编辑
我尝试了 this.props.history.replaceState 并且似乎毫无问题地通过了状态。它仅在 onEnter 钩子(Hook)中不起作用。

编辑 2
在对 react 进行了更多的实验和学习之后,我意识到我正在使用 react 进行服务器端渲染。 replaceState 函数将在服务器中触发,Router.match 函数(推荐用于服务器端渲染)将触发:
    Router.match({ routes: routes.default, location: req.url }, function(err, redirectLocation, renderProps) {
if (err) {
res.status(500).send(err.message)
} else if (redirectLocation) {
res.status(302).redirect(redirectLocation.pathname + redirectLocation.search)
} else if (renderProps) {
var html = ReactDOM.renderToString(React.createElement(Router.RoutingContext, renderProps));
var page = swig.renderFile('views/index.html', { html: html });
res.status(200).send(page);
} else {
res.status(404).send('Page Not Found')
}
});

redirectLocation 将设置为“/login”,并且 renderProps 将包含下一个状态。但显然在进行服务器端重定向时,nextState 不会传递:
res.status(302).redirect(redirectLocation.pathname + redirectLocation.search)
如果这是正确的,那么问题是如何在服务器端重定向时设置状态。

最佳答案

在组件中。 pathName 在 this.props.location.pathname 中
我在那里得到它。

_handleSubmit: function(e) {
e.preventDefault();
//console.log(this.props.location.state); // null ???
//the above should be changed to
console.log(this.props.location.pathname);
return false;
}

关于react-router - 在 onEnter 中使用 replaceState 时 this.props.location.state 为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34789698/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com