反应-使用地图功能遍历状态

时间:2018-09-17 18:06:52

标签: javascript reactjs iteration state setstate

我对React和创建ToDoList样式Recipe App相对较新。用户应该能够将新食谱添加到列表中,以及删除或编辑现有食谱。

我遇到了一个问题,使配料分别显示在单独的行上,而asked this question则显示如何执行此操作。最终结果是,我在容器中添加了第二个.map函数以遍历所有成分并将每个成分显示为新的段落元素。这是我的容器Item.js

import React from 'react';
import Button from 'react-bootstrap/lib/Button';


const Item = (props) => (
  <div>
    <div className="Recipe-Item-Container" key={props.text}>
      {/* Iterates through recipe item names and displays them */}
      {props.items.map((item, index) => {
        return (
        <div className="Recipe-Item" key={index}>
          <h3>{item}</h3>

         // This is what I added
        {/* Iterates through recipe ingriedients and displays them*/}
        <p className="ingredients-list">
          {props.ingredients[index].map((ingredient, ingredientIndex) => {
            return (
              <div className="ingredient" key={ingredient}>
                {ingredient}
              </div>
            )
          })}
        </p>

        <div className="buttons-container">
          <Button className="edit-button" onClick={() => props.edit(item, index)}>Edit</Button>
          <Button className="delete-button" onClick={() => props.delete(item, index)}>Delete</Button>
          </div>
        </div>
      );
    }
  )}
  </div>
</div>
)

export default Item;

现在,我所在州的初始配方可以在新行中正确显示配料,并且用户编辑的任何配方项目也可以在新行中显示配料。正是我想要的。

问题是,当用户添加新食谱时,配料没有按照我想要的方式显示在新行中。如果单击添加新配方按钮并添加一个新配方按钮,则成分将并排显示为一个段落元素。

我有两个功能,分别用于添加新配方和编辑现有配方onSubmitonEditSubmitonEditSubmit可以正常工作,因为编辑配方时,配料会在单独的行中正确显示。 onSubmit是问题所在。如何更改onSubmit并使其在新行和单独的段落中显示成分?我认为这是我如何在onSubmit中设置状态的问题,并且可能涉及使用散布运算符。

这是我的App.js

import React, { Component } from 'react';
import Item from './Item';
import './App.css';
import ModalComponent from './Modal.js';
import Button from 'react-bootstrap/lib/Button';
import EditModalComponent from './EditModal.js';
import SimpleStorage from "react-simple-storage";


export default class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      items: ["Pumpkin Pie", "Spaghetti", "Onion Pie"],
      ingredients:[
        ["Pumpkin Puree ", "Sweetened Condensed Milk ", "Eggs ", "Pumpkin Pie Spice ", "Pie Crust "],
        ["Noodles ", "Tomato Sauce ", "(Optional) Meatballs "],
        ["Onion ", "Pie Crust "]
      ],

      // Recipe name and ingredients
      inputVal: '',
      ingredientVal: '',
      // Recipe name and ingredients when user is editing existing recipe
      inputValEdit: '',
      ingredientValEdit: '',
      // Controls whether forms are displayed or hidden
      showRecipeForm: false,
      showRecipeEditForm: false,
      // Index to select which recipe item is being edited
      editingIndex: ''
    };

  }

  // Get text user inputs for recipes
  handleChange = (event) => {
    this.setState({ [event.target.name]: event.target.value });
  };


  // When user submits recipe this adds it to the list
  onSubmit = (event) => {
    event.preventDefault();

    this.setState({
      items: [...this.state.items, this.state.inputVal],
      ingredients: [...this.state.ingredients, [this.state.ingredientVal]],
      showRecipeForm: false
    });

  }

  // When user edits existing recipe this adds it to the list
  onEditSubmit = (event) => {
    event.preventDefault();
    const {items, ingredients, inputValEdit, ingredientValEdit, editingIndex} = this.state;

    // Selects proper recipe item to edit
    items[editingIndex] = inputValEdit;
    ingredients[editingIndex] = ingredientValEdit.split(',');


    this.setState({
      items: items,
      ingredients: ingredients,
      inputVal: '',
      ingredientVal: '',
      showRecipeEditForm: false
    });
  }

  closeRecipeForm = () => {
    this.setState({
      showRecipeForm: false,
      showRecipeEditForm: false
    });
  }

  // Shows recipe
  AddRecipe = (bool) => {
    this.setState({
      showRecipeForm: bool
    });
  }

  // Is called when one of the edit recipe buttons is clicked, shows RecipeEditForm
  edit = (item, index) => {
    this.setState({
      showRecipeEditForm: !this.state.showRecipeEditForm,
      editingIndex: index
    });
  }

  // Deletes recipe item from the list
  delete = (item, index) => {
     this.setState({
      ingredients : this.state.ingredients.filter((_, i) => i !== index),
      items: this.state.items.filter((_, i) => i !== index)
    });
  }


  render() {
    return (
      <div className="container">

        {/* Handles storing data in local sessions via react-simple-storage*/}
        <SimpleStorage parent={this} />

        <h1>Recipe List</h1>


        <ModalComponent
          inputVal={this.state.inputVal}
          handleChange={this.handleChange}
          ingredientVal={this.state.ingredientVal}
          onSubmit={this.onSubmit}
          addRecipe={this.addRecipe}
          showRecipeForm={this.state.showRecipeForm}
          closeRecipeForm={this.closeRecipeForm}
        />

        <EditModalComponent
          inputValEdit={this.state.inputValEdit}
          handleChange={this.handleChange}
          ingredientValEdit={this.state.ingredientValEdit}
          onEditSubmit={this.onEditSubmit}
          closeRecipeForm={this.closeRecipeForm}
          addRecipe={this.addRecipe}
          showRecipeEditForm={this.state.showRecipeEditForm}
        />


        <Item
          items={this.state.items}
          ingredients={this.state.ingredients}
          edit={this.edit}
          delete={this.delete}
        />

      <Button className="add-recipe-button" onClick={this.AddRecipe}>Add New Recipe</Button>

      </div>
    );
  }

}

我是否需要使onSubmitonEditSubmit更相似?如果可以,我该怎么做?

1 个答案:

答案 0 :(得分:1)

在商店中,您的成分变量是一个数组数组。[ [a, b] , [c, d]]

您需要像在onEditSubmit中一样遵循这种格式。 .split()函数返回一个数组并将其保存为状态。

在onSubmit中更改零件

this.setState({
    items: [...this.state.items, this.state.inputVal],
    ingredients: [...this.state.ingredients, [this.state.ingredientVal]],
    showRecipeForm: false
});

this.setState({
    items: [...this.state.items, this.state.inputVal],
    ingredients: [...this.state.ingredients, this.state.ingredientVal.split(',')],
    showRecipeForm: false
});