【问题标题】:ReactRouter doesn't redirect correctly after flux notification通量通知后 ReactRouter 无法正确重定向
【发布时间】:2016-10-24 16:20:19
【问题描述】:

我是 React 和 Flux 的新手。事实上,我在使用 ReactRouter (2.4) 时偶然发现了以下问题

我正在使用 hashHistory,在成功登录尝试后,我在“/login”页面时需要重定向到“/”页面。

路由器

ReactDOM.render(
<Router history={hashHistory}>
    <Route path="/" component={App}>
        <IndexRoute component={ErasmusPage} onEnter={authCheck}></IndexRoute>
        <Route path="login"component={withRouter(LoginPage)}></Route>
    </Route>
</Router>, app);

登录页面

constructor() {
    super();
    this.notifyLogin = this.notifyLogin.bind(this);
    this.state = {
        email: "",
        password: ""
    };
}

componentWillMount() {
    authStore.on("login", this.notifyLogin);
}

componentWillUnmount() {
    authStore.removeListener("login", this.notifyLogin);
}

notifyLogin() {
    this.props.router.push('/');
}

...

handleSubmit(e) {
    e.preventDefault();

    let data = {
        email: this.state.email,
        password: this.state.password
    };
    AuthActions.authenticate(data);
}
...

流程是:

  1. 提交后,authActions 和 Store 详细说明数据(涉及 ajax 调用)。
  2. 如果登录尝试正常,AuthStore 会发出“登录”信号...
  3. ...所以我可以执行 notifyLogin()。

问题是:this.props.router.push('/') 没有正确重定向,它改变了 URL 而不是页面(看起来状态刷新没有被触发)。

奇怪的是,如果我将 this.props.router.push('/') 放在 handleSubmit 函数中,重定向会完美运行。

知道发生了什么吗?

【问题讨论】:

    标签: redirect reactjs ecmascript-6 react-router flux


    【解决方案1】:

    到目前为止,这对我来说效果很好:

    • 将您的应用包装在包含登录/身份验证状态的组件中。
    • 在渲染时,如果未登录,则渲染登录页面组件,否则,渲染应用组件

    render() {
      const { isAuthorized, authError} = this.props;
      
      if (isAuthorized) {
        return (<Layout />);
      }
      
      return (<Login authError={authError}/>);
    }

    【讨论】:

    • 嗯,是的。我知道我能做到。不过,重点是使用来自商店的通知来触发调用组件内部的开关。我挖得更深,我相信这与调用堆栈有关。商店中的发射调用组件中的“通知”,而不是在同一个调用中我尝试交换组件但堆栈调用试图在错误的上下文中向后退......它一定是这样的......跨度>
    • 嗯,越来越相信如果我进行异步回调它可能会起作用,我尝试使用:setTimeout(() => { this.props.router.push('/'); }, 1000);它有效,但它是一个黑客......有人有更好的主意吗?将 axios 的承诺传递给商店而不是在回调中调度是错误的吗?
    • 啊,好的@user3549754,你的组件只是触发了一个登录动作。如果登录成功,该操作会调度一个 user_authenticated 操作,该操作会在登录存储中设置该操作。现在您的登录商店将收到新的道具。添加一个 componentWillUpdate,如果 userAuthenticated 属性为 true,则重定向。
    • 嗯,所以,即使我想将事物隔离在较低的组件中,我想最好的方法是在父节点中放置“userAuthenticated”状态。它会让我省去很多汗水,毕竟,解决方案是干净的。感谢您的帮助。真的!
    • 当然,很高兴为您提供帮助。
    猜你喜欢
    • 1970-01-01
    • 2015-04-29
    • 1970-01-01
    • 2015-01-18
    • 1970-01-01
    • 2015-09-26
    • 1970-01-01
    • 2017-01-09
    • 2019-09-14
    相关资源
    最近更新 更多