Redux存储不会随着反应状态的改变而改变

时间:2018-07-09 11:41:12

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

我正在尝试根据当前状态更改来更改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}  />       

2 个答案:

答案 0 :(得分:2)

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

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

mapDispatchToProps API Documentation

答案 1 :(得分:0)

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

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