如何使用用户输入的数据将对象添加到数组?

问题描述 投票:0回答:1

我正在构建一个食谱应用程序,允许用户添加自定义食谱,然后显示它们。

我能够添加一个配方就很好,但是当我添加第二个配方时,它将更改第一个配方,使其具有与第二个相同的数据。

Screenshot of Recipe App Issue

配方列表的初始状态设置为空数组:

recipeList: [],
  newRecipe: {
    title: '',
    source: '',
    id: ''

[每次点击提交食谱按钮时,我都希望能够向阵列添加新食谱并将其显示为缩略图(请参见上面的屏幕截图)。新配方采​​用对象的形式,并且如上所示,新配方对象的初始状态设置为空。因此,从本质上讲,我希望能够将新的用户输入放入新的配方对象中,将其添加到空数组中,并将整个数组显示为配方缩略图。

在React Dev Tools中,我在阵列中看到了两个配方,所以我知道它们已经添加了。但是由于某些原因,它们无法正确显示。

Screenshot of Array Items in Dev Tools

提交后,数组中的每个项目都被映射并作为缩略图返回:

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}
          />
        ))}

因此map()方法可能会出现问题,因为它似乎没有通过正确的数组进行映射。

这是我提交表单以添加新食谱时触发的功能:

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)
};

[将数组映射到上方时,它将返回一个名为<RecipeCardThumbnail />的组件。这是该组件的代码:

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>
  );

除了未显示每个项目外,我还收到一条错误消息,指出每个孩子都需要唯一的键。我以为我拥有的ID可以作为密钥。

不确定此代码是否足够,但是您可以在此处查看整个代码:Recipe App on Github

javascript arrays reactjs object user-input
1个回答
1
投票

乍一看,您似乎应该在这里使用recipe的属性,而不是this.state

所以这个:

{this.state.recipeList.map((recipe) => (
  <RecipeCardThumbnail
    key={recipe.id}
    title={recipe.title}
    source={recipe.source}
  />
))}

代替此:

{this.state.recipeList.map((recipe) => (
  <RecipeCardThumbnail
    key={this.state.id}
    title={this.state.title}
    source={this.state.source}
  />
))}
© www.soinside.com 2019 - 2024. All rights reserved.