简体   繁体   中英

React.js: State not getting update before url redirect

I have a currentUser object in App.state that starts out as an empty object before the user is logged in and gets set with the user's information once the user successfully logs in.

Upon a successful login, I call setState({currentUser: user}) which prompts an update. Then, in componentDidUpdate() , I check whether a change to currentUser prompted the update, and if it did, I call window.location.href = "/home" , and render a <Home /> component.

  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
    }
  }

in render() :

  <Route
    path="/home"
    render={(props) => (
      <Home currentUser={this.state.currentUser} />
    )}
  />

The problem is, when the user gets redirected to /home , this.props.currentUser is still an empty object in the 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 a prop.

What am I misunderstanding here?

window.location.href is a valid way to change the route. However, this actually causes a reload or a refresh of the entire page. It is similar to how you manually type this url in the browser. Therefore, all the states are removed or cleared.

As suggested in this link , you are supposed to use the following:

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

And in order to pass parameters, you may check this link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM