【问题标题】:React Add Item with spread operator使用扩展运算符反应添加项目
【发布时间】:2019-02-07 20:53:58
【问题描述】:

我的问题是关于 React 添加和编辑项目。我想在数组中添加对象(对象包含数量、数量单位、数组中的名称)console.log 可以,但没有添加对象。在我的表单上,无法显示此功能的结果。我想从 API 添加新的 ingredietns 列表对象。我不知道我是否有不好的道具或状态

import React, { Component } from "react";
import {
  FormGroup,
  FormControl,
  ControlLabel,
  InputGroup
} from "react-bootstrap";
export default class AddIngredient extends Component {
  constructor(props) {
    super(props);
    this.state = {
      ingredients: [],
      amount: " ",
      amountUnit: " ",
      name: " "
    };
  }

  onChangeAmount = e => {
    this.setState({ amount: e.target.value });
    console.log("amount was changed");
  };

  onChangeAmountUnit = e => {
    this.setState({ amountUnit: e.target.value });
    console.log("amount unit was changed");
  };
  onChangeName = e => {
    this.setState({ name: e.target.value });
    console.log("name was changed");
  };

  onClickAddIngredient = e => {
    const { amount, amountUnit, name } = this.state;
    const newIngredient = { amount, amountUnit, name };
    this.setState({ ingredients: [...this.state.ingredients, newIngredient] });

    console.log("was added");
  };

  render() {
    const { amount, amountUnit, name } = this.props;
    return (
      <React.Fragment>
        <FormGroup>
          <ControlLabel>Přidat ingredienci</ControlLabel>
          <InputGroup className="frow">
            <FormControl
              type="number"
              placeholder="Množství"
              min="0"
              value={amount}
              onChange={this.onChangeAmount}
            />
            <FormControl
              type="text"
              placeholder="Jednotka"
              value={amountUnit}
              onChange={this.onChangeAmountUnit}
            />
          </InputGroup>
          <InputGroup>
            <FormControl
              type="text"
              placeholder="Název"
              value={name}
              onChange={this.onChangeName}
            />
            <InputGroup.Addon>
              <button onClick={this.onClickAddIngredient} className={"addon"}>
                Přidat
              </button>
            </InputGroup.Addon>
          </InputGroup>
        </FormGroup>
      </React.Fragment>
    );
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

import React, { Component } from "react";

import IngredientItems from "./IngredientItems";
import AddIngredient from "./AddIngredient";
import Directions from "./Directions";
import { FormGroup, Button, ButtonGroup, Grid } from "react-bootstrap";
import BasicInfo from "./BasicInfo";
export default class RecipeForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      title: props.title || "",
      servingCount: props.servingCount,
      preparationTime: props.preparationTime,
      sideDish: props.sideDish,
      directions: props.directions,
      ingredients: props.ingredients
    };
  }

  onChange = (key, value) => {
    this.setState({ [key]: value });
  };

  render() {
    const { onCancel } = this.props;
    const {
      ingredients,
      title,
      servingCount,
      sideDish,
      preparationTime,
      directions
    } = this.state;

    return (
      <Grid>
        <ButtonGroup
          className="pull-right"
          size="lg"
          aria-label="Basic example"
        >
          <Button onClick={this.onSave} bsStyle="success">
            Uložit
          </Button>
          <Button onClick={onCancel} bsStyle="default">
            Zrušit
          </Button>
        </ButtonGroup>
        <BasicInfo
          title={title}
          preparationTime={preparationTime}
          servingCount={servingCount}
          sideDish={sideDish}
          onChange={this.onChange}
        />
        <IngredientItems ingredients={ingredients} />
        <Directions directions={directions} onChange={this.onChange} />
        <AddIngredient onChange={this.onChange} />
        <FormGroup />
      </Grid>
    );
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

【问题讨论】:

    标签: javascript reactjs object add


    【解决方案1】:

    您的 AddIngredient 组件中有本地状态 ingredients,但它从未真正呈现。

    看起来您想要做的是向该组件传递一个处理程序,该处理程序会更新父组件中的ingredient 数组。

    AddIngredient.js

    onClickAddIngredient = e => {
      const { amount, amountUnit, name } = this.state;
      const newIngredient = { amount, amountUnit, name };
    
      // call handler from parent and update there
      this.props.onAdd(newIngredient);
    
      console.log("was added");
    };
    

    RecipeForm.js

    onAddIngredient = (newIngredient) => {
      this.setState({ ingredients: [...this.state.ingredients, newIngredient] });
    };
    

    此外,您似乎不需要将onChange 传递给该组件,因为输入字段只是保持在其本地状态。所以你可以像这样添加新的处理程序来渲染它:

    <AddIngredient onAdd={this.onAddIngredient} />
    

    然后你可以删除子组件中的本地状态ingredients,因为它没有被使用。

    【讨论】:

      猜你喜欢
      • 2020-02-09
      • 1970-01-01
      • 2020-12-20
      • 2018-04-21
      • 2020-12-20
      • 1970-01-01
      • 2018-10-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多