Javascript Redux reducer正在被React组件中的setState或.map()写入

Javascript Redux reducer正在被React组件中的setState或.map()写入,javascript,reactjs,redux,Javascript,Reactjs,Redux,当我将this.state.orginalSeries、this.props.demandGraphSeriesDataReducer和newSeries记录到中时,我会返回所有相同的变异数据 我尝试使用.map()和.slice()来不改变原始的reducer数据,但它仍然在改变。我还可以看到,使用Redux Devtools,它也在改变减速器的状态 class DemandSubDemand extends Component { constructor(props) { sup

当我将
this.state.orginalSeries
this.props.demandGraphSeriesDataReducer
newSeries
记录到
中时,我会返回所有相同的变异数据

我尝试使用.map()和.slice()来不改变原始的reducer数据,但它仍然在改变。我还可以看到,使用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>
}

类需求SubDemand扩展组件{
建造师(道具){
超级(道具);
此.state={
orginalSeries:空
};
}
componentDidMount(){
const copy=this.props.demandGraphSeriesDataReducer.slice()
这是我的国家({
原创系列:复制
})
}
componentDidUpdate(prevProps、prevState){
if(this.props.demandGraphSeriesDataReducer!==prevProps.demandGraphSeriesDataReducer){
const copy=this.props.demandGraphSeriesDataReducer.slice()
这是我的国家({
原创系列:复制
})
}
}
onValueUpdate(i,值){
const newSeries=this.state.orginalSeries.map((行,j)=>{
如果(i==j)行数据[i]=行数据[i]+值;
回流线;
});
}
render(){
在此处返回此.onValueUpdate(0100)}>
}
使用
JSON.parse(JSON.stringify(this.props.demandGraphSeriesDataReducer))
代替
切片
按照@icepickle的建议工作

我认为突变可能在这里:

onValueUpdate(i,值){
const newSeries=this.state.orginalSeries.map((行,j)=>{
如果(i==j)行数据[i]=行数据[i]+值;
回流线;
});
}
特别是,
line.data[i]=
将改变原始数组中现有的
line
对象。你需要让它不变异


我强烈建议您使用,它默认添加了一个变异检查器。此外,考虑使用更简单的不可变更新。默认情况下,Redux Starter Kit在内部使用Immer。

我看不到任何地方有减速器,也看不到您如何为组件使用
connect
,甚至在可能调用它的地方。您似乎只是处理本地状态,而您的道具可能来自一个减速机或它的父组件,来自您共享的代码。但是,当您使用
map
时,您的
确实会引用数组中的原始条目,您可以在映射之前使用
切片
(但由于某些原因,
onValueUpdate
方法中没有
this.setState
,因此它不应该重新呈现组件父组件连接到存储,该存储传递demandGraphSeriesDataReducer,这是一个reducer。这可能是您可以加入的部分:)但是我关于
引用数组原始条目的评论仍然适用,您确实在对
originalSeries
和reducer中的原始数组项进行变异。
slice
不做deepcopy,如果您想要deepcopy并且没有循环引用,您应该使用
J做得更好parse(JSON.stringify(this.props.demandGraphSeriesDataReducer))
。将数组命名为reducer可能会有问题……啊,这样做了。这并不漂亮,但很有效。谢谢,伙计!太好了,我个人不介意在需要执行对象的完整副本时使用此解决方案:)