簡體   English   中英

React.js:State 在 url 重定向之前沒有得到更新

[英]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一個道具。

我在這里有什么誤解?

window.location.href是更改路線的有效方法。 但是,這實際上會導致重新加載或刷新整個頁面。 它類似於您在瀏覽器中手動鍵入此 url 的方式。 因此,所有狀態都被刪除或清除。

正如此鏈接中所建議的,您應該使用以下內容:

this.props.history.push('/home')

為了傳遞參數,您可以查看此鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM