【问题标题】:React input field isn't updatableReact 输入字段不可更新
【发布时间】:2022-02-01 13:12:01
【问题描述】:

我有一个 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;

【问题讨论】:

  • 您可能只需将onChange 属性更改为onChange={ (e) =&gt; handleChange(e) }
  • 在这种情况下这两件事是等价的。
  • 啊,我认为必须明确传递事件。我在下面看到你的答案 - 好眼力

标签: javascript reactjs api next.js


【解决方案1】:

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

job 看起来并没有改变,我想你想改用form,因为它正在更新。

【讨论】:

    【解决方案2】:

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

    <Form.Control
                    type="text"
                    placeholder="Enter Salary"
                    name="salary"
                    value={form.salary}
                    onChange={handleChange}
                  />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-02
      • 2012-04-03
      • 2019-07-20
      • 1970-01-01
      • 2021-07-30
      相关资源
      最近更新 更多