[英]the props change when the state change
我有usersList
數組來自 api 請求
react-redux
, and then i store the usersList
coming from api in my state
in getDerivedStateFromProps
static getDerivedStateFromProps(props, state) {
const newState = {};
if(state.usersList !== props.usersList && props.usersList.length > 0 && props.loadingStep === '3'){
newState.usersList = props.usersList;
}
return newState;
}
render
function 中顯示usersList
數組的內容,用戶可以編輯或不編輯信息。this.state
this.setState({ usersList:newList }); // where the newList contain the new info
問題
問題是用戶何時可能想要撤消該更改。 所以我想用 this.props.usersList 中的舊信息更新this.props.usersList
但我發現this.props.usersList
包含與 state 中相同的信息
console.log(this.state.usersList) // [1,2,3, ... the new info]
console.log(this.props.usersList) // [1,2,3, ... the new info]
我的問題是:
為什么this.props.usersList
隨着this.state.usersList
的更新而更新
newState.usersList = props.usersList;
創建對 props.usersList 的引用。 因此它將始終引用 usersList。
嘗試克隆props.usersList
數組:
newState.usersList = [...props.usersList];
使用擴展運算符“...”,您可以輕松地將數組克隆到新數組中,而不僅僅是參考。
這有幫助嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.