Javascript 如何使用来自用户输入的数据将对象添加到数组中?
我正在构建一个配方应用程序,允许用户添加自定义配方,然后显示它们 我可以添加一个配方,但当我添加第二个配方时,它会更改第一个配方,使其与第二个配方具有相同的数据 配方列表的初始状态设置为空数组:Javascript 如何使用来自用户输入的数据将对象添加到数组中?,javascript,arrays,reactjs,object,user-input,Javascript,Arrays,Reactjs,Object,User Input,我正在构建一个配方应用程序,允许用户添加自定义配方,然后显示它们 我可以添加一个配方,但当我添加第二个配方时,它会更改第一个配方,使其与第二个配方具有相同的数据 配方列表的初始状态设置为空数组: recipeList: [], newRecipe: { title: '', source: '', id: '' 每次我点击submit Recipe按钮时,我都希望能够向数组中添加一个新的配方,并将其显示为缩略图(请参见上面的屏幕截图)。新配方以对象的形式出现,如上
recipeList: [],
newRecipe: {
title: '',
source: '',
id: ''
每次我点击submit Recipe按钮时,我都希望能够向数组中添加一个新的配方,并将其显示为缩略图(请参见上面的屏幕截图)。新配方以对象的形式出现,如上所示,新配方对象的初始状态设置为空。因此,本质上我希望能够将新的用户输入放入新的recipe对象,将其添加到空数组中,并将整个数组显示为recipe缩略图
在React-Dev工具中,我在数组中看到了这两个菜谱,因此我知道它们正在被添加。但由于某些原因,它们没有正确显示
提交后,数组中的每个项目都会映射并作为缩略图返回:
return (
<div className="App">
<Navbar />
<div className='app-body'>
{this.state.recipeList.map((recipe) => (
<RecipeCardThumbnail
key={this.state.id}
title={this.state.title}
source={this.state.source}
/>
))}
})
下面是添加新配方的函数:
handleSubmitNewRecipe = e => {
e.preventDefault();
this.handleAddNewRecipe(this.state.title, this.state.source, this.state.id);
handleAddNewRecipe = (title, source) => {
const newRecipe = {
title: title,
source: source,
id: (Math.floor(Math.random()* 1000))
}
this.setState({recipeList: [...this.state.recipeList, newRecipe] });
console.log(this.state.recipeList)
};
当数组被映射时,它返回一个名为
的组件。以下是该组件的代码:
return (
<div className="card select thumbnail-card">
<div className="card-body">
<h5 className="card-title">{this.props.title}</h5>
<h6 className='card-subtitle text-muted'>{this.props.source}</h6>
<ul className="qty-details">
<li >{this.props.servings}</li>
<li >{this.props.prepTime}</li>
<li >{this.props.cookTime}</li>
<li >{this.props.totalTime}</li>
</ul>
</div>
</div>
);
返回(
{this.props.title}
{this.props.source}
- {this.props.servings}
- {this.props.prepTime}
- {this.props.cookTime}
- {this.props.totalTime}
);
除了没有显示每个项目之外,我还得到一个错误,即每个子项都需要一个唯一的键。我以为我的身份证是一把钥匙
不确定这是否是足够的代码,但您可以在此处查看整个代码:乍一看,您似乎应该在此处使用
配方的属性,而不是此.state
因此:
{this.state.recipeList.map((配方)=>(
))}
与此相反:
{this.state.recipeList.map((配方)=>(
))}
不要发布代码、数据、错误消息等的图像-复制或在问题中键入文本。