反应重定向不显示正确的组件

时间:2018-12-19 20:06:35

标签: reactjs react-router

我有一个react应用,该应用在登录方法中应该重定向到/ profile路由。路径正在更改,但是Profile组件未呈现。我认为这可能与路线的顺序或使用的确切路径有关。我试过使用和从react-router-dom。刷新页面是可行的,但是将当前用户注销。链接通过导航栏而不是this.props.history.push(/ profile)起作用。谢谢!

class App extends Component {
 constructor(props){
 super(props)
 this.state = {
  currentUser: null,
  loggedIn: false,
  unauthorizedUser: false
 }

this.handleLoginSubmit = this.handleLoginSubmit.bind(this);
 }

  async handleLoginSubmit(e) {
   e.preventDefault()
   const url = 'http://localhost:3000/auth/login';
   const options = {
   method: 'POST',
   headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
   },
   body: JSON.stringify({
    email: e.target[0].value,
    password: e.target[1].value
   })
  }

   await fetch(url, options)
    .then(res => res.status === 200 ? res.json() : "Unauthorized")
     .then(payload => {
      if (payload !== "Unauthorized") {
      window.localStorage.setItem("token", payload.token)
      this.setState({ loggedIn: true,
        currentUser: payload.user.id,
        unauthorizedUser: false,
        userfirstName: payload.user.firstName,
        userlastName: payload.user.lastName
      });
      console.log('current user is ' + this.state.currentUser)
      this.props.history.push(`/profile`);
      } else {
       this.setState({ loggedIn: false, unauthorizedUser: true })
      }
    })
    .catch(err => {
      console.log(err);
    })

 }

 render() {
   return (
  <div className="App">
    <Router>
      <div>
        <Nav loggedIn={this.state.loggedIn} handleLogout={this.handleLogout}/>
        <Route exact path='/profile' render={props => <Profile {...props} currentUser={this.state.currentUser} firstName={this.state.userfirstName} lastName={this.state.userlastName}/>} />
        <Route exact path='/' render={props => <HomePage {...props} handleLoginSubmit={this.handleLoginSubmit}
          handleSignUpSubmit={this.handleSignUpSubmit} unauthorizedUser = {this.state.unauthorizedUser} signUpError = {this.state.signUpError}
          loggedIn={this.state.loggedIn}/>}/>
        <Route exact path='/update' render={props => <UpdateUser {...props} currentUser={this.state.currentUser}/> }/>

        <Route exact path='/createoutfit' render={props => <AddOutfit {...props} currentUser={this.state.currentUser}/> }/>
        <Route exact path='/items' component={Items} />
        <Route exact path='/items/new' render={props => <AddItem {...props} currentUser={this.state.currentUser}/> } />
        <Route exact path='/outfits' render={props => <Outfit {...props} currentUser={this.state.currentUser}/> }/>
        <Route exact path='/add/itemstoOutfit' render={props => <AddItemsToOutfit {...props} currentUser={this.state.currentUser}/> }/>

        <Route exact path='/items/upload' component={FileUpload}/>

      </div>
    </Router>
  </div>
    );
  }
}

export default withRouter(App);

1 个答案:

答案 0 :(得分:0)

我认为您应该在setState操作完成后运行this.props.history.push代码,如下所示:

this.setState({ loggedIn: true,
    currentUser: payload.user.id,
    unauthorizedUser: false,
    userfirstName: payload.user.firstName,
    userlastName: payload.user.lastName
}, () => {
    console.log('current user is ' + this.state.currentUser)
    this.props.history.push(`/profile`);
});

https://reactjs.org/docs/react-component.html#setstate

  

setState()并不总是立即更新组件。它可能会批量更新或将更新推迟到以后。这使得在调用setState()之后立即读取this.state可能是一个陷阱。而是使用componentDidUpdate或setState回调(setState(updater,callback)),确保在应用更新后均能触发这两种方法。如果需要基于先前的状态来设置状态,请阅读以下有关updater参数的信息。