javascript - 有没有办法在状态下修改数组中的元素
问题描述
我正在尝试以某种状态修改数组中的元素。假设我想修改“id”。
class example extends Component {
state = {
recipes: [{
id: 5
}]
}
changeID = (newID, arrayIndex) => {
}
我需要输入什么changeID
来修改id?
解决方案
你可以使用这样的东西:
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 });
}
推荐阅读
- typescript - TypeScript 中的“复合类型”
- sql-server - 如何将多月数据放入多列
- git - 使用 Visual Studio 代码在 Visual Studio Team Server(或 gitlab)上创建远程 git 存储库
- c++ - 在排序的文本文件中实现二进制搜索?
- angularjs - 使用 ng-options 和 'as' 设置标签('track by' 替代方案)
- python - 从 Sage 中提取单一解决方案
- javascript - React 中状态更新时动态更改获取请求 url
- events - Google 表格 onEdit 事件不起作用
- android - google sheet自定义菜单功能在android上的google sheet中不可见
- laravel - 如何使用 openssl 通过 HTTPS 保护 apache 本地服务器?