【问题标题】:How to access history props in componentWillMount?如何访问 componentWillMount 中的历史道具?
【发布时间】:2018-12-28 04:43:10
【问题描述】:

在我的主页中,我有一个存储注册和登录按钮的组件。

Homepage.js

state = {
    triggerSignInComponent: false
}

render() {
   return {
    this.state.triggerButtons ? 
      <div>
        <Link to='/register'>
          <button>Register</button>
        <Link/>

        <button onClick={this.toggleSignInHandler}>Sign In</button>
      </div> : null
   }
}
  • 如果用户点击登录,该组件将调用登录组件。
  • 如果用户点击注册,他们将被重定向到注册组件。但是,如果他们改变主意,则会有一个登录按钮,可将用户重定向回主页并切换登录组件。

Register.js

signInHandler = () => {
    this.props.history.push({
        pathname:'/',
        state: {
            triggerSignInComponent: true
        }
    });
}

<button onClick={this.onSubmitHandler}>Register</button> 

<button onClick={this.signInHandler}>Sign In</button>

我希望在用户切换 signInHandler 后立即显示登录组件。如果用户被重定向到主页进行登录,我如何更改主页的状态?我在 Homepage.js 中尝试了以下内容:

componentWillMount = () => {
    if(this.props.location.state.triggerSignInComponent) {
        this.setState({
            triggerSignInComponent: true
        })
    }
}

但是,这不起作用,因为在第一次调用组件时未定义 prop。

【问题讨论】:

  • 你在用 react-router 吗?
  • 是的! Link 标签是 react-router-dom 的一部分。
  • 不要用withRouter HOC 来包装你的组件,以便获得位置、历史...等道具
  • withRouter 是你的朋友
  • 感谢您的提示。但是,它仍然无法像最初那样工作,当组件挂载时,主页没有可用的历史道具可供访问。

标签: javascript reactjs react-router react-router-dom


【解决方案1】:

尝试将 this.props.location.state.triggerSignInComponent 更改为 this.props.location.triggerSignInComponent

componentWillMount = () => {
    if(this.props.location.triggerSignInComponent) {
        this.setState({
            triggerSignInComponent: true
        })
    }
}

【讨论】:

  • 感谢您的建议,但它仍然说triggerSignInComponent 未定义。
  • 再试一次,在您的 register.js 文件中,从 'react-router-dom' 导入 { withRouter },然后在文件末尾导出默认的 withRouter(Register);
  • 我应该注意到Register.js是连接到Redux的,所以最终是export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Register))。但是,这仍然表明triggerSignInComponent 未定义。
猜你喜欢
  • 2019-05-09
  • 2018-01-26
  • 1970-01-01
  • 1970-01-01
  • 2020-02-20
  • 2018-06-29
  • 1970-01-01
  • 2020-08-09
  • 2022-01-16
相关资源
最近更新 更多