Redux还原器正在通过我的React组件中的SetState或.map()编写



当i console.log this.state.orginalSeriesthis.props.demandGraphSeriesDataReducernewSeries时,我将获得所有相同的突变数据。

我尝试使用.map((和.slice((不突变原始的还原数据,而是尝试突变的方式。我还可以看到使用redux devtools也正在突变还原器的状态。

class DemandSubDemand extends Component {
  constructor(props) {
    super(props);
    this.state = {
      orginalSeries: null
    };
  }
  componentDidMount(){
    const copy = this.props.demandGraphSeriesDataReducer.slice()
    this.setState({
      orginalSeries: copy
    })
  }
  componentDidUpdate(prevProps, prevState) {
    if (this.props.demandGraphSeriesDataReducer!== prevProps.demandGraphSeriesDataReducer) {
      const copy = this.props.demandGraphSeriesDataReducer.slice()
      this.setState({
        orginalSeries: copy
      })
    }
  }
  onValueUpdate(i, value) {
    const newSeries = this.state.orginalSeries.map((line, j) => {
      if(i === j) line.data[i] = line.data[i] + value;
      return line;
    });
  }
render(){
  return <button onClick={()=>this.onValueUpdate(0,100)}> here</button>
}

i 认为突变可能在这里:

  onValueUpdate(i, value) {
    const newSeries = this.state.orginalSeries.map((line, j) => {
      if(i === j) line.data[i] = line.data[i] + value;
      return line;
    });
  }

特别是,line.data[i] =将在原始数组中突变现有的line对象。您需要在数据中添加各个层次的嵌套副本,以使其不突变。

我强烈鼓励您使用Redux启动器套件中的configureStore()功能,该功能默认情况下会添加突变检查器。另外,请考虑使用浸入器以进行简单的不变更新。Redux入门套件的createReducer()createSlice()函数默认使用内部使用。

使用JSON.parse( JSON.stringify( this.props.demandGraphSeriesDataReducer ) )代替slice的工作@icepickle的建议

最新更新