簡體   English   中英

state 更改時道具更改

[英]the props change when the state change

我有usersList數組來自 api 請求

  1. i handle the data coming from api with 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;
  }
  1. 我在render function 中顯示usersList數組的內容,用戶可以編輯或不編輯信息。
  2. 當用戶編輯信息時,我將新信息保存在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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM