【问题标题】:Redux store doesn't change with the change of react stateRedux 存储不会随着反应状态的变化而变化
【发布时间】:2018-12-17 02:09:57
【问题描述】:

我正在尝试根据当前状态更改更改 redux 存储,状态更改正确,但 this.props 仍然作为初始化。这是我的代码:

componentWillMount(){
    this.props.fetchMatches();
  }

  handleChange(newDateRange){
    console.log('====================================');
    console.log('handleChange fired');
    console.log(this.state);
    console.log('====================================');
  }


function mapDispatchToProps(dispatch) {
  return {
    handleChange: (newDateRange) =>
      dispatch({
      ...this.props.home,
      startDate: newDateRange[0],
      endDate: newDateRange[1]
    })
  }
}

export default connect(mapStateToProps, { mapDispatchToProps, fetchMatches })(Home);

这是DateRange的实现:

<DateRangeInput className="daterange" value={[this.props.startDate, this.props.endDate]} onChange={this.handleChange}  />       

【问题讨论】:

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


    【解决方案1】:
    function mapDispatchToProps(dispatch, ownProps) {
      return {
        handleChange: (newDateRange) =>
          dispatch({
          ...ownProps.home,
          startDate: newDateRange[0],
          endDate: newDateRange[1]
        })
      }
    }
    

    https://github.com/reduxjs/redux-devtools/issues/250

    【讨论】:

    • 当我更改DateRange 的值时,这不会运行,我怎样才能在调用handleChange 函数时触发它?
    • this.props.handleChange([startDate, endDate])
    • &lt;DateRangeInput value={[this.props.startDate, this.props.endDate]} onChange={this.props.handleChange} /&gt; 我怎么能在这里做到这一点?
    • 我不知道DateRangeInput 是如何工作的,你能用handleChange handleChange: (v) => console.log(v) 记录结果吗
    • 没有调用!不记录任何东西!
    【解决方案2】:

    您不能从这里访问 mapDispatchToProps 中的道具,因为即使在组件安装之前调用了该函数。而是从 mapDispatchToProps 访问它,它在第二个参数中公开了先前的道具。

    function mapDispatchToProps(dispatch, ownProps) {
      return {
        handleChange: (newDateRange) =>
          dispatch({
          ...ownProps.home,
          startDate: newDateRange[0],
          endDate: newDateRange[1]
        })
      }
    }
    

    mapDispatchToProps API Documentation

    【讨论】:

    • 当我更改DateRange 的值时,这不会运行,我怎样才能在调用handleChange 函数时触发它?
    • 你能分享一下 DateRange 的实现吗?我也可以问一下为什么 connect 中的第二个参数是一个对象而不是一个对象:export default connect(mapStateToProps, mapDispatchToProps)(Home);
    • 如果你传入一个对象作为 connect() 的第二个参数,它假定你已经给它一个 prop 名称的映射给动作创建者,所以它会自动通过 bindActionCreators 运行所有它们实用程序并将结果用作道具。目前以 { mapDispatchToProps, fetchMatches } 作为第二个参数,react-redux 假定 mapDispatchToPropsfetchMatches 都是动作创建者。检查这个question
    猜你喜欢
    • 2023-01-10
    • 1970-01-01
    • 2020-10-21
    • 2020-09-10
    • 2021-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-01
    相关资源
    最近更新 更多