![](/img/trans.png)
[英]React component not getting redux's initial state set by reducer
[英]Redux reducer is getting over written by setState or .map() in my React component
當我 console.log this.state.orginalSeries
, this.props.demandGraphSeriesDataReducer
和newSeries
我得到所有相同的變異數據。
我嘗試使用 .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>
}
我認為突變可能在這里:
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 Starter Kit 中的configureStore()
函數,它默認添加了一個變異檢查器。 此外,考慮使用Immer進行更簡單的不可變更新。 Redux Starter Kit 的createReducer()
和createSlice()
函數默認在內部使用 Immer。
使用JSON.parse( JSON.stringify( this.props.demandGraphSeriesDataReducer ) )
代替slice
按照 @icepickle 的建議工作
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.