簡體   English   中英

在React中設置狀態時如何更新數組中的項目

[英]How to update an item in array while setting state in react

我需要幫助來優化此代碼

eatMushroom = (foundMushroom, startTime, steps) => {
  const updatedMushrooms = this.state.mushrooms;
  updatedMushrooms[foundMushroom.key].remaining = false;
  this.setState({
    mushrooms: updatedMushrooms,
    score: this.state.score + 1
  });

  if (this.totalMushrooms === this.state.score) {
    this.props.setTotalTime(startTime, steps);
    this.props.history.push("/score");
  }
};

當我只想更新一個項目時,這會在替換完整陣列的狀態時降低性能。

為了更好的實踐,首先應該避免改變狀態,如果在更新狀態時需要狀態的值,則應考慮使用功能狀態更新。 這將有助於始終獲得正確的值。

要考慮的另一件事是您在設置它后立即使用this.state.score setState是異步的,可以在執行if語句后發生。 為此,您應該考慮使用回調。

以下是帶有上述建議的代碼的修改版本;

this.setState((prevState) => {
  const mushrooms = Object.assign({}, prevState.mushrooms);
  mushrooms[foundMushroom.key].remaining = false;
  return { mushrooms, score: (prevState.score + 1) };
}, () => {
  if (this.totalMushrooms === this.state.score) {
    this.props.setTotalTime(startTime, steps);
    this.props.history.push("/score");
  }
});

我不知道您如何使用this.state.mushrooms值,但是為了獲得更好的性能,您可以做一些更改。 如果只想修改一個屬性,則應將屬性上移一個級別。 我認為mushrooms屬性是不必要的。

示例數據

而不是像下面這樣使用

this.state = {
  mushrooms: {
    mushA: {
      remaining: true
    },
    mushB: {
      remaining: false
    },
    mushC: {
      remaining: true
    }
  }
};

你可以這樣使用

this.state = {
  mushA: {
    remaining: true
  },
  mushB: {
    remaining: false
  },
  mushC: {
    remaining: true
  }
};

這樣,您可以像下面那樣更新狀態。 一次擁有一個屬性,我相信這將導致更好的性能更新。

this.setState((prevState) => {
  const mushroom = Object.assign({}, prevState[foundMushroom.key], { remaining: false });
  return { [foundMushroom.key]: mushroom, score: (prevState.score + 1) };
}, () => {
  if (this.totalMushrooms === this.state.score) {
    this.props.setTotalTime(startTime, steps);
    this.props.history.push("/score");
  }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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