onChange事件不会在第一个输入上触发

时间:2020-08-02 01:33:52

标签: reactjs components react-hooks reactstrap react-hook-form

我是React的新手,我有一个注册(父组件),其中有一个库存(子组件),一旦用户输入了他们要订购的物品的数量,我就更改库存状态按住以便我可以注册它们

但是onChange似乎被延迟了,例如,我输入了4个水瓶,并且只有当我输入其他项(例如食物)的金额时,控制台才会记录我的默认值,它向我显示4个水瓶和0个食物:(

这就是我正在使用的...

子组件:

import React from "react";
import { Col, Row, FormGroup, Label, Input } from "reactstrap";

import waterIcon from "./../assets/water.png";
import soupIcon from "./../assets/food.png";
import medsIcon from "./../assets/aid.png";
import weaponIcon from "./../assets/gun.png";

function Inventory({ onSubmitInventory, currentInventory }) {
  const onChangeWater = (e) => {
    const newInventory = { ...currentInventory, water: e.target.value };
    onSubmitInventory(newInventory);
  };

  const onChangeSoup = (e) => {
    const newInventory = { ...currentInventory, soup: e.target.value };
    onSubmitInventory(newInventory);
  };

  const onChangeMeds = (e) => {
    const newInventory = { ...currentInventory, meds: e.target.value };
    onSubmitInventory(newInventory);
  };

  const onChangeWeapon = (e) => {
    const newInventory = { ...currentInventory, weapon: e.target.value };
    onSubmitInventory(newInventory);
  };

  return (
    <FormGroup>
      <Row className="justify-content-center text-center border-top pt-3">
        <Col xs="3">
          <img src={waterIcon} alt="Water" />
          <Label for="inventoryWater">Fiji Water:</Label>
          <Input
            type="number"
            name="inventoryWater"
            id="inventoryWater"
            placeholder="Enter amount..."
            onChange={onChangeWater}
          />
        </Col>
        <Col xs="3">
          <img src={soupIcon} alt="Soup" />
          <Label for="inventorySoup">Campbell Soup:</Label>
          <Input
            type="number"
            name="inventorySoup"
            id="inventorySoup"
            placeholder="Enter amount..."
            onChange={onChangeSoup}
          />
        </Col>
        <Col xs="3">
          <img src={medsIcon} alt="Aid" />
          <Label for="inventoryMeds">First Aid Pouch:</Label>
          <Input
            type="number"
            name="inventoryMeds"
            id="inventoryMeds"
            placeholder="Enter amount..."
            onChange={onChangeMeds}
          />
        </Col>
        <Col xs="3">
          <img
            className="d-block"
            style={{ margin: "0 auto" }}
            src={weaponIcon}
            alt="Gun"
          />
          <Label for="inventoryWeapon">AK47:</Label>
          <Input
            type="number"
            name="inventoryWeapon"
            id="inventoryWeapon"
            placeholder="Enter amount..."
            onChange={onChangeWeapon}
          />
        </Col>
      </Row>
    </FormGroup>
  );
}

export default Inventory;

父组件:

import React, { useState } from "react";
import { Col, Row, Button, Form, Label, Input } from "reactstrap";
import { useForm } from "react-hook-form";

import Inventory from "./Inventory";
import MapContainer from "./MapContainer";

function Register() {
  const [lonlat, setLonlat] = useState("");
  const onMarkerChange = (lonlat) => {
    setLonlat(lonlat);
  };

  const [inventory, setInventory] = useState({
    water: 0,
    soup: 0,
    meds: 0,
    weapon: 0,
  });
  const onSubmitInventory = (newInventory) => {
    setInventory(newInventory);
    console.log(inventory);
  };

  const { register, handleSubmit, errors } = useForm();
  const onSubmit = (data) => {
    console.log(inventory);
    const requestOptions = {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ name: data.personName }),
    };
    console.log(data);
  };

  return (
    <Form
      id="registerForm"
      name="registerForm"
      onSubmit={handleSubmit(onSubmit)}
    >
      <h4>New Person</h4>
      <Row className="border-top pt-4">
        <Col xs="8">
          <Label for="personName">Your name:</Label>
          <Input
            className="gray-input"
            type="text"
            name="name"
            id="personName"
            placeholder="Enter your name here..."
            innerRef={register}
          />
        </Col>
        <Col xs="2" className="text-center">
          <Label for="personAge">Age:</Label>
          <Input
            className="gray-input"
            type="number"
            name="age"
            id="personAge"
            placeholder="Enter age..."
            innerRef={register}
          />
        </Col>
        <Col xs="2" className="text-center">
          <Label for="personGender">Gender:</Label>
          <Input
            type="select"
            name="gender"
            id="personGender"
            innerRef={register}
          >
            <option defaultValue disabled>
              -
            </option>
            <option>F</option>
            <option>M</option>
          </Input>
        </Col>
      </Row>
      <Row>
        <Col xs="12">
          <Input
            hidden
            id="personLatLon"
            name="personLatLon"
            type="text"
            defaultValue={lonlat}
            innerRef={register}
          />
          <MapContainer onMarkerChange={onMarkerChange} />
        </Col>
      </Row>
      <h4>Inventory</h4>
      <Inventory
        onSubmitInventory={onSubmitInventory}
        currentInventory={inventory}
      />
      <Button
        outline
        color="secondary"
        className="mt-2"
        type="submit"
        form="registerForm"
      >
        Submit
      </Button>
    </Form>
  );
}

export default Register;

编辑:更新了代码,提供了来自答案的提示,仍然面临着同样的问题:(

2 个答案:

答案 0 :(得分:2)

我在您的代码中看到的唯一问题是您正在尝试将第二个参数传递给const result = []; for(let i = 1; i < ?? ; i++) { const test = document.getElementById('test').innerHTML; result.push({ test }) } return { result } }) 。我不认为这可以像处理类组件那样与钩子一起使用。当我尝试在打字稿中键入内容时,会立即引发错误。

只需传递您要发送的实际数据,然后调用setInventory,例如:

onSubmitInventory(inventory)

如果您必须等待下一个渲染调用 const onChangeWeapon = (e) => { const newInventory = {...inventory, weapon: e.target.value}; setInventory(newInventory); onSubmitInventory(newInventory); }; ,则它应该是父级的onSubmitInventory。我的下一个问题是,为什么父母需要状态而孩子也将状态作为状态?可能应该将其提起。但是我不确定没有见到父母。


编辑:您的问题只是useEffect吗?如果您运行

console.log

state的值在下一次渲染之前不会更改。调用const [state, setState] = useState(true); // ... setState(false); console.log(state); // outputs true. 将导致一个新的渲染,但是直到那一刻,旧值才出现。在父级中像这样在体内添加setState状态

console.log

您会看到它的更新!

在这种情况下,状态值不变的事实可能会咬你:

const [inventory, setInventory] = useState({
    water: 0,
    soup: 0,
    meds: 0,
    weapon: 0,
  });
console.log('I just rendered, inventory: ', inventory);

因此,如果在渲染之前我有两次调用setState的可能性,我将使用这种形式:

const [state, setState] = useState(true); // closes over this state!
// ...
setState(!state); // closes over the state value above
setState(!state); // closes over the same state value above
// state will be false on next render

答案 1 :(得分:1)

在父组件的onSubmitInventory内,您已将参数命名为inventory,但该参数已存在于父组件的作用域中。我建议重命名newInventory以便明确您要引用的对象。

此外,似乎您在父母和孩子的状态下都在跟踪库存。将其保留在父母中,然后作为道具传递给孩子。