代码之家  ›  专栏  ›  技术社区  ›  Nick Kinlen

React-使用map函数遍历状态

  •  0
  • Nick Kinlen  · 技术社区  · 6 年前

    我比较新的反应和创造一个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 ingredients 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;
    

    现在,我的状态中的初始配方会在新行上正确显示配料,用户编辑的任何配方项也会在新行上显示配料。正是我想要的。

    我有两个函数来处理添加新配方和编辑现有配方, onSubmit onEditSubmit OneEdit提交 工作正常,因为编辑食谱时,配料会正确地显示在单独的行上。 是个问题。我怎样才能改变 让它在新行和单独的段落中显示成分?我认为这是一个问题,我是如何设置内的状态 提交

    这是我的 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>
        );
      }
    
    }
    

    我需要做些什么吗 更类似于 ? 如果是这样,我怎么能做到?

    1 回复  |  直到 4 年前
        1
  •  1
  •   skyboyer    6 年前

    在您的商店中,您的配料变量是一个数组数组。 [ [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
    });