加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

react-router – 在onEnter中使用replaceState时,this.props.loc

发布时间:2020-12-15 20:49:15 所属栏目:百科 来源:网络整理
导读:我一直在关注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
我一直在关注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挂钩时才起作用.

编辑2
经过实验和学习更多关于反应的知识后,我意识到我正在做反应的服务器端渲染. 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;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读