gpt4 book ai didi

javascript - 我如何在食谱对象数组中编辑食谱对象

转载 作者:行者123 更新时间:2023-11-30 20:32:25 25 4
gpt4 key购买 nike

我正在使用 React 制作一个食谱盒项目,为了编辑现有的食谱,我尝试了这段代码,this.state.recipe当前是一个配方对象数组:

editRecipe = (recipe) => {
this.state.recipe.find(obj => obj.name === recipe.name).name = recipe.name;
this.state.recipe.find(obj => obj.name === recipe.name).ingredients = recipe.ingredients;
}

并将此方法传递给 <EditRecipe edit={this.editRecipe} />作为 Prop 。但是,当我激活该组件中的方法而不是调用 edit Prop 时,会出现一条错误消息:“this.state.recipe.find(...) is undefined”

还有其他方法可以编辑食谱吗?

这是我收到的错误消息 enter image description here

谢谢。

最佳答案

箭头函数没有自己的this

来自 MDN

An arrow function expression has a shorter syntax than a function expression and does not have its own this, arguments, super, or new.target. These function expressions are best suited for non-method functions, and they cannot be used as constructors.

不确定,但您可以尝试使用常规函数:

editRecipe = function(recipe){
this.state.recipe.find(obj => obj.name === recipe.name).name = recipe.name;
this.state.recipe.find(obj => obj.name === recipe.name).ingredients =
recipe.ingredients;
}

关于javascript - 我如何在食谱对象数组中编辑食谱对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50196170/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com