【发布时间】: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 获得的isAuthenticated 和redirect 值都是正确的)。
你能告诉我错误在哪里吗?为什么 history 对象没有被更新,即使其他一切似乎都正常运行? (Redux 状态发生变化 - 第二次渲染时在 App 组件中清晰可见,渲染 Redirect 并且我的浏览器中的 url 更改为正确的一个)
更新:
当我将console.log 放入App 组件中的componentDidUpdate 方法时,它会显示this.props.history.location 的正确值。
更新 2:
当我将日志放入App 和Auth 组件中的render 和componentDidUpdate 方法并点击登录按钮时,这就是结果。
App 和 Auth 都被渲染,而 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