我正在将React类更改为React Hooks,并在onChange()函数的设置状态上出现错误

时间:2019-12-10 10:05:17

标签: javascript reactjs react-hooks use-effect

我将context代码从类更改为React Hooks,并在设置ReactJs函数的状态时出错。 新旧代码都在下面提到。只能通过onChange()方法发出问题。

onChange()方法的主要目的是获取值并设置状态。因此,按下添加按钮后,它将保存到数据库。

预先感谢您帮助我解决问题。

新代码

onChange()

旧代码


        import React, { useState, useEffect } from "react";
        import { Form } from "../Layout";
        import axios from "axios";
        import { store as notifications } from "react-notifications-component";
        import BootstrapTable from "react-bootstrap-table-next";
        import cellEditFactory from "react-bootstrap-table2-editor";

        const Topping = () => {
          const [toppings, setToppings] = useState([]);
          const [topping, setTopping] = useState("");
          const [price, setPrice] = useState(0);

          const onChange=(e)=> {
            const { name, value } = e.target;
            setToppings({toppings, [e.target.name]: e.target.value });
            //console.log("toppings", toppings);
          }
          useEffect(() => {
            getTopping();
          }, []);

          const getTopping = () => {
            axios
              .get("/topping/")
              .then(res => {
                setToppings(res.data);
              })
              .catch(err => console.log(err));
          };

          const addToppingAction = e => {
            e.preventDefault();
            const pizza = {
              name: topping,
              price: price
            };
            axios
              .post("/topping/add", pizza)
              .then(res => {
                notifications.addNotification({
                  message: res.data.topping,
                  type: "success",
                  insert: "top",
                  container: "bottom-right",
                  dismiss: {
                    duration: 2000
                  }
                });
                getTopping();
                setTopping("");
                setPrice(0);
              })
              .catch(err =>
                notifications.addNotification({
                  message: err.data,
                  type: "danger",
                  insert: "top",
                  container: "bottom-right",
                  dismiss: {
                    duration: 2000
                  }
                })
              );
          };
          function handleDelete(topping) {
            if (window.confirm("Delete Topping?" + topping.name)) {
              axios
                .get("/topping/delete/" + topping._id)
                .then(res => {
                  notifications.addNotification({
                    message: res.data,
                    type: "success",
                    insert: "top",
                    container: "bottom-right",
                    dismiss: {
                      duration: 5000
                    }
                  });
                  this.getTopping();
                })
                .catch(err => {});
            } else {
              notifications.addNotification({
                message: "action Cancelled",
                type: "danger",
                insert: "top",
                container: "bottom-right",
                dismiss: {
                  duration: 5000
                }
              });
            }
          }
          const columns = [
            { dataField: "_id", text: "ID", hidden: true },
            { dataField: "name", text: "Toppings" },
            { dataField: "price", text: "price" },
            {
              dataField: "databasePkey",
              text: "Remove",
              editable: false,
              formatter: (cellContent, sizes) => {
                return (
                  <button
                    className="btn btn-danger btn-xs"
                    onClick={() => handleDelete(sizes)}
                  >
                    x
                  </button>
                );
              }
            }
          ];
          const cellEditProps = {
            mode: "click",
            blurToSave: true,
            beforeSaveCell(oldValue, newValue, row, column, done) {
              if (window.confirm("Apply Changes?")) {
                axios
                  .post("/topping/update/" + row._id, row)
                  .then(res => {
                    notifications.addNotification({
                      message: res.data,
                      type: "success",
                      insert: "top",
                      container: "bottom-right",
                      dismiss: {
                        duration: 5000
                      }
                    });
                  })
                  .catch(err => {
                    console.log(err);
                    notifications.addNotification({
                      message: "Update Error",
                      type: "danger",
                      insert: "top",
                      container: "bottom-right",
                      dismiss: {
                        duration: 5000
                      }
                    });
                  });
                done(); // contine to save the changes
              } else {
                notifications.addNotification({
                  message: "action Cancelled",
                  type: "danger",
                  insert: "top",
                  container: "bottom-right",
                  dismiss: {
                    duration: 5000
                  }
                });
                done(false); // reject the changes
              }
              return { async: true };
            }
          };
          console.log("toppings", toppings);
          return (
            <div className="row">
              <div className="col-12 col-md-4">
                <h5>Add Topping</h5>
                <Form onSubmit={addToppingAction} className="pb-4">
                  <div className="form-group">
                    <label className="col-form-label" htmlFor="topping">
                      Topping
                    </label>
                    <input
                      type="text"
                      name="topping"
                      value={topping}
                      onChange={onChange}
                      placeholder="Topping"
                      className="form-control"
                    />
                  </div>
                  <div className="form-group">
                    <label className="col-form-label" htmlFor="price">
                      Price
                    </label>
                    <input
                      type="number"
                      step="0.1"
                      name="price"
                      value={price}
                      onChange={onChange}
                      placeholder="Price"
                      className="form-control"
                    />
                  </div>

                  <button className="btn btn-outline-secondary" type="submit">
                    Add Toppings
                  </button>
                </Form>
              </div>
              <div className="col-12 col-md-8">
                <h5>Click to edit Topping</h5>
                {/* <BootstrapTable
                  keyField="_id"
                  data={toppings}
                  columns={columns}
                  cellEdit={cellEditFactory(cellEditProps)}
                />*/}
              </div>
            </div>
          );
        };

        export default Topping;

2 个答案:

答案 0 :(得分:0)

您应该使用数组参数作为初始值调用setToppings 并在更改中使用对象调用它

const onChange=(e)=> {
  const { name, value } = e.target;
  if (name === 'toppings') {
    setToppings(e.target.value);
  }
  if (name === 'price') {
    setPrice(e.target.value);
  }
}

答案 1 :(得分:0)

您正在使用数组作为初始值,并使用对象更新状态。我认为这行不通。

此外,您还应该使用传播运算符将先前的值“插入”新对象:

setToppings({...toppings, [e.target.name]: e.target.value})