[英]React.js: State not getting update before url redirect
我在App.state
中有一個currentUser
object,它在用戶登錄之前以空 object 開始,並在用戶成功登錄后使用用戶信息進行設置。
成功登錄后,我調用setState({currentUser: user})
提示更新。 然后,在componentDidUpdate()
中,我檢查對currentUser
的更改是否提示了更新,如果是,我調用window.location.href = "/home"
,並渲染一個<Home />
組件。
componentDidUpdate(prevProps, prevState) {
// if the user just successfully logged in, redirect to home
if (
Object.keys(prevState.currentUser).length === 0 && // was an empty object
Object.keys(this.state.currentUser).length > 0 // now it's been set
) {
window.location.href = "/home"; // render the Home component, passing this.state.currentUser as a prop
}
}
在render()
:
<Route
path="/home"
render={(props) => (
<Home currentUser={this.state.currentUser} />
)}
/>
問題是,當用戶被重定向到/home
時, this.props.currentUser
中仍然是一個空的Home.props
。 So even though an update to this.state.currentUser
(where it explicitly isn't an empty object anymore) is what triggered the change to the /home
Route, this.state.currentUser
is still an empty object when I pass it down as一個道具。
我在這里有什么誤解?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.