【问题标题】:React redirect not displaying correct component反应重定向不显示正确的组件
【发布时间】:2019-05-20 08:55:28
【问题描述】:

我有一个反应应用程序,在登录方法中它应该重定向到 /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);

【问题讨论】:

  • 请显示配置文件组件代码

标签: reactjs react-router


【解决方案1】:

我认为你应该在 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 参数。

【讨论】:

    猜你喜欢
    • 2018-06-09
    • 2017-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-03
    • 2021-11-22
    • 1970-01-01
    相关资源
    最近更新 更多