【问题标题】:Redirect component is rendered but won't change history object重定向组件被渲染但不会改变历史对象
【发布时间】:2019-02-26 17:03:31
【问题描述】:

我遇到了这个问题。登录成功后,我将 redux 状态的 redirect 属性设置为我要重定向到的路径。我的 redux 状态正在正确更新。在我的 Auth 组件中,我可以看到 Redirect 组件已呈现,并且浏览器中的 url 更改为该特定路径。然而在我的父组件中,当我访问 history 对象时,它仍然显示旧的 url,因此 Switch 组件选择了错误的路径。

render() {
  console.log(this.props.history.location);
  
  return (
    <div className="App">
      <p>{this.props.redirect}</p>
      <Switch>
        <Route path="/home" render={() => <p>Home page</p>} />
        <Route path="/" component={Auth} exact />
      </Switch>     
    </div>
  );
}

这里,console.log 的输出是 /(旧路径),this.props.redirect 显示 /home(这是正确的新路径)。

这里是 Auth 组件。

let authRedirect = null;
if (this.props.isAuthenticated && this.props.redirect) {
  authRedirect = <Redirect to={this.props.redirect} />
}

console.log(authRedirect)

return (
  <div className="Auth">
    {authRedirect}
    {form}
  </div>
);

控制台日志记录authRedirect 表明,一旦用户登录,它就拥有正确的Redirect 组件(从redux 获得的isAuthenticatedredirect 值都是正确的)。

你能告诉我错误在哪里吗?为什么 history 对象没有被更新,即使其他一切似乎都正常运行? (Redux 状态发生变化 - 第二次渲染时在 App 组件中清晰可见,渲染 Redirect 并且我的浏览器中的 url 更改为正确的一个)

更新:

当我将console.log 放入App 组件中的componentDidUpdate 方法时,它会显示this.props.history.location 的正确值。

更新 2:

当我将日志放入AppAuth 组件中的rendercomponentDidUpdate 方法并点击登录按钮时,这就是结果。 AppAuth 都被渲染,而 history.location.pathname 仍设置为 /auth 但 redux 状态正确设置为 /。只有在 componentDidUpdate 中渲染了组件后,history.location.pathname 才能正确设置。

[APP RENDER], location.pathname: /auth, redux - redirect: /
[AUTH RENDER], location.pathname: /auth, redux - redirect: /
[AUTH UPDATE], location.pathname: /, redux - redirect: /
[APP UPDATE], location.pathname: /, redux - redirect: /

【问题讨论】:

  • redux store 更新后你的路由组件会刷新吗?
  • @aravind_reddy Route 组件所在的整个父组件刷新为正确的 redux 状态。
  • 所以在你的 console.log 中它给出了两次相同的值?
  • @aravind_reddy 确切地说,控制台日志记录 this.props.history.location 两次给出相同的值
  • 你的连接组件是否使用 withRouter 组件/包装器?

标签: javascript reactjs redux react-router-dom


【解决方案1】:

在目标页面,你可以从历史监听中获取更新的路径名

this.props.history.listen(location => {
  if (location.pathname !== this.props.location.pathname) {
    this.props.location.pathname = location.pathname;
    this.forceUpdate();
  }
});

在我的例子中,我创建了状态 URL 并从 componentDidMount 更新它

componentDidMount() {
    this.props.history.listen(location => {
        if(location) {
            this.setState({
                url: location.pathname
            })    
        }
    });
}

【讨论】:

    猜你喜欢
    • 2018-12-31
    • 2019-09-22
    • 1970-01-01
    • 1970-01-01
    • 2020-02-13
    • 2023-03-08
    • 1970-01-01
    • 2021-08-09
    • 1970-01-01
    相关资源
    最近更新 更多