[英]Redux reducer is getting over written by setState or .map() in my React component
When I console.log the this.state.orginalSeries
, this.props.demandGraphSeriesDataReducer
and newSeries
I get all of the same mutated data back.当我 console.log
this.state.orginalSeries
, this.props.demandGraphSeriesDataReducer
和newSeries
我得到所有相同的变异数据。
I tried using .map() and .slice() to not mutate the original reducer data but some how it still is getting mutated.我尝试使用 .map() 和 .slice() 来不改变原始的减速器数据,但它仍然是如何变异的。 I can also see using Redux Devtools it is mutating the state of the reducer as well.
我还可以看到使用 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 think the mutation may be here:我认为突变可能在这里:
onValueUpdate(i, value) {
const newSeries = this.state.orginalSeries.map((line, j) => {
if(i === j) line.data[i] = line.data[i] + value;
return line;
});
}
In particular, line.data[i] =
is going to mutate the existing line
object in the original array.特别是,
line.data[i] =
将改变原始数组中现有的line
对象。 You would need to make copies of every level of nesting in the data for it to not mutate.您需要复制数据中每个嵌套级别的副本,以免发生变异。
I'd strongly encourage you to use the configureStore()
function from Redux Starter Kit , which adds a mutation checker by default.我强烈建议您使用Redux Starter Kit 中的
configureStore()
函数,它默认添加了一个变异检查器。 Also, consider using Immer for simpler immutable updates.此外,考虑使用Immer进行更简单的不可变更新。 Redux Starter Kit's
createReducer()
and createSlice()
functions use Immer internally by default. Redux Starter Kit 的
createReducer()
和createSlice()
函数默认在内部使用 Immer。
使用JSON.parse( JSON.stringify( this.props.demandGraphSeriesDataReducer ) )
代替slice
按照 @icepickle 的建议工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.