繁体   English   中英

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

[英]How to add an object to an array using data from user input?

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

我可以添加一个配方就好了,但是当我添加第二个配方时,它会将第一个配方更改为与第二个配方具有相同的数据。

食谱应用问题的屏幕截图

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

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

每次我点击提交食谱按钮时,我都希望能够向数组添加一个新食谱并将其显示为缩略图(见上面的截图)。 新配方是一个对象的形式,如上所示,新配方对象的初始状态设置为空。 所以基本上我希望能够将新的用户输入放入新的配方对象中,将其添加到空数组中,并将整个数组显示为配方缩略图。

在 React 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 可以用作密钥。

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

乍一看,您似乎应该在这里使用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}
  />
))}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM