开发者问题收集

React 输入字段不可更新

2022-02-01
83

我有一个 React/Next 应用,可以在其中发布笔记/工作。我有一个编辑或更新按钮,单击后,我会获得原始帖子的状态以及填充的输入字段,但可以编辑或在输入字段中输入任何新内容。我的 onChange={handleChange} 有什么问题吗?我没有得到它。

谢谢

const EditJob = ({ job }) => {
  const [form, setForm] = useState({
    title: job.title,
    company: job.company,
    location: job.location,
    salary: job.salary,
    status: job.status,
    contact: job.contact,
    note: job.note,
  });
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setErrors] = useState({});
  const router = useRouter();

  const handleSubmit = (e) => {
    e.preventDefault();
    let errs = validate();
    setErrors(errs);
    setIsSubmitting(true);
  };

  const handleChange = (e) => {
    setForm({
      ...form,
      [e.target.name]: e.target.value,
    });
  };

  useEffect(() => {
    if (isSubmitting) {
      if (Object.keys(error).length === 0) {
        updateJob();
      } else {
        setIsSubmitting(false);
      }
    }
  }, [error]);

  const updateJob = async () => {
    try {
      const res = await fetch(
        `http://localhost:3000/api/jobs/${router.query.id}`,
        {
          method: "PUT",
          headers: {
            Accept: "application:json",
            "Content-Type": "application/json",
          },
          body: JSON.stringify(form),
        }
      );
      router.push("/");
    } catch (error) {
      console.log(error);
    }
  };

  const validate = () => {
    let err = {};

    if (!form.title) {
      err.title = "Title is required";
    }
    if (!form.company) {
      err.company = "Company is required";
    }
    if (!form.location) {
      err.description = "Location is required";
    }

    return err;
  };

  return (
    <Container>
      <h1>Update Job</h1>
      <div>
        {isSubmitting ? (
          <Spinner animation="border" />
        ) : (
          <Row>
            <Col>
              <Form onSubmit={handleSubmit}>
                <Form.Group className="mb-3">
                  <Form.Label>Job Title</Form.Label>
                  <Form.Control
                    error={
                      error.title
                        ? {
                            content: "Please enter a job title",
                            pointing: "below",
                          }
                        : null
                    }
                    label="Title"
                    placeholder="Job Ttile"
                    name="title"
                    value={job.title}
                    onChange={handleChange}
                  />
                </Form.Group>
                <Form.Group className="mb-3">
                  <Form.Label>Company</Form.Label>
                  <Form.Control
                    type="text"
                    placeholder="Enter company name"
                    name="company"
                    value={job.company}
                    onChange={handleChange}
                  />
                </Form.Group>
                <Form.Group className="mb-3">
                  <Form.Label>Location</Form.Label>
                  <Form.Control
                    type="text"
                    placeholder="Enter location"
                    name="location"
                    value={job.location}
                    onChange={handleChange}
                  />
                </Form.Group>
                <Form.Group className="mb-3">
                  <Form.Label>Salary</Form.Label>
                  <Form.Control
                    type="text"
                    placeholder="Enter Salary"
                    name="salary"
                    value={job.salary}
                    onChange={handleChange}
                  />
                </Form.Group>
                <Form.Group className="mb-3">
                  <Form.Label>Status</Form.Label>
                  <Form.Control
                    type="text"
                    placeholder="Just applied"
                    name="status"
                    value={job.status}
                    onChange={handleChange}
                  />
                </Form.Group>
                <Form.Group className="mb-3">
                  <Form.Label>Contact</Form.Label>
                  <Form.Control
                    type="text"
                    placeholder="Is there a contact?"
                    name="contact"
                    value={job.contact}
                    onChange={handleChange}
                  />
                </Form.Group>
                <Form.Group className="mb-3">
                  <Form.Label>Note</Form.Label>
                  <Form.Control
                    as="textarea"
                    placeholder="Add notes here"
                    style={{ height: "100px" }}
                    name="note"
                    value={job.note}
                    onChange={handleChange}
                  />
                </Form.Group>
                <Button type="submit">Update</Button>
              </Form>
            </Col>
          </Row>
        )}
      </div>
    </Container>
  );
};

EditJob.getInitialProps = async ({ query: { id } }) => {
  const res = await fetch(`http://localhost:3000/api/jobs/${id}`);
  const { data } = await res.json();

  return { job: data };
};

export default EditJob;
2个回答

由于这些是受控输入,因此值始终是您输入的 value

job 看起来永远不会改变,我认为您想使用 form ,因为它正在更新。

windowsill
2022-02-01

尝试使用这样的值。 使用 form.salary 而不是 job.salary

<Form.Control
                type="text"
                placeholder="Enter Salary"
                name="salary"
                value={form.salary}
                onChange={handleChange}
              />
zeeshan zahoor
2022-02-01