【问题标题】:setState of a component before rendering next component React-Redux [duplicate]渲染下一个组件React-Redux之前组件的setState [重复]
【发布时间】:2018-03-07 04:54:02
【问题描述】:

我有一个点击按钮,我正在导航到另一个组件

<Link to="/result"><button onClick = {this.setDealSizeAndType} name="patient">Calculate</button></Link>

  setDealSizeAndType({ target }){

    const dealTypeName = target.name ;
    this.setState({
      dealType: dealTypeName
    }, function(){
        this.props.setDealType(this.state.dealType);
    });
  }

function mapDispatchToProps(dispatch){
  return {
    setDealType: (dealType) =>{
      dispatch(setType(dealType));
    }
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Calculator);

但状态尚未设置。我越来越不确定。我必须在与此组件无关的下一个组件中获取此值。有什么办法,我可以在渲染下一个组件之前设置状态。

【问题讨论】:

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


    【解决方案1】:

    您可以动态导航,而不是使用链接

    <button onClick = {this.setDealSizeAndType} name="patient">Calculate</button>
    
      setDealSizeAndType({ target }){
    
        const dealTypeName = target.name ;
        this.setState({
          dealType: dealTypeName
        }, function(){
            this.props.setDealType(this.state.dealType);
            this.props.history.push('/result');  // Programmatically navigate like this
        });
      }
    
    function mapDispatchToProps(dispatch){
      return {
        setDealType: (dealType) =>{
          dispatch(setType(dealType));
        }
      }
    }
    
    export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Calculator));
    

    你可以在How to Programmatically navigate using react router查看这个答案

    【讨论】:

      【解决方案2】:

      你可以在调用 onclick 处理程序时使用绑定函数,所以这里是更新的代码

      <Link to="/result"><button onClick = {this.setDealSizeAndType.bind(this,'patient')}>Calculate</button></Link>
      

      现在在 setDealSizeAndType 函数中,您将直接收到名称。

       setDealSizeAndType(name){
      
      const dealTypeName = name ;
      this.setState({
        dealType: dealTypeName
      }, function(){
          this.props.setDealType(this.state.dealType);
      });
      }
      

      希望对你有帮助

      【讨论】:

        猜你喜欢
        • 2021-04-28
        • 2018-03-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-10
        • 1970-01-01
        • 1970-01-01
        • 2023-03-28
        相关资源
        最近更新 更多