首页 > 解决方案 > 有没有办法在状态下修改数组中的元素

问题描述

我正在尝试以某种状态修改数组中的元素。假设我想修改“id”。

class example extends Component {

  state = {
    recipes: [{
      id: 5
    }]
  }
  changeID = (newID, arrayIndex) => {
  
  }

我需要输入什么changeID来修改id?

标签: javascriptreactjs

解决方案


你可以使用这样的东西:

function changeID(ID){
  const { recipes } = this.state;
  const filteredRecipes = recipes.filter(item => item.id === ID);
  
  /*
    Any logic to change the element here!
    You can check if the element exists before doing anything.
  */
  const recipe = filteredRecipes.shift();
  const updatedRecipe = { ...recipe, id:6 }

  //And if you want to update the state...
  const updatedRecipes = [ ...recipes, updatedRecipe ];
  this.setState({ recipes: updatedRecipes });
}

推荐阅读