【问题标题】:Edit mode doesn't show class attributes in React编辑模式在 React 中不显示类属性
【发布时间】:2021-07-21 15:07:51
【问题描述】:

我在一个表单中进行了创建和编辑两种模式,但是当我尝试编辑元素时出现问题,我得到了正确的 id 值但无法检索属性值。

import { yupResolver } from "@hookform/resolvers/yup";
import { useState, useEffect } from "react";
import { useForm, SubmitHandler } from "react-hook-form";
import { useParams, useHistory, Link } from "react-router-dom";
import * as yup from "yup";
import {
  getChoice,
  postChoice,
  updateChoice,
} from "../../../../api/remote.api";
import { CustomInput } from "../../../../components/lib";
import { Choice } from "../../../../models";

type Inputs = {
  displayMessage: string;
  value: string;
};

const schema = yup.object().shape({
  displayMessage: yup.string().min(5, "Au minimum 5 chars").required(),
  value: yup.string().min(5, "Au minimum 8 chars").required(),
});

const NewChoice = () => {
  const { id } = useParams<{ id?: string }>();
  const isAddMode = !id;

  let history = useHistory();
  const [submitting, setSubmitting] = useState<boolean>(false);
  const [error, setError] = useState<string>();
  const {
    register,
    handleSubmit,
    setValue,
    formState: { errors },
  } = useForm<Inputs>({ resolver: yupResolver(schema) });

  const onSubmit: SubmitHandler<Inputs> = (data: Inputs) => {
    setSubmitting(true);
    const choice = new Choice({
      displayMessage: data.displayMessage,
      value: data.value,
      id: Number(id) ? Number(id) : -1,
    });

    submitForm(choice, id)
      .then((chc) => {
        setSubmitting(false);
        history.goBack();
      })
      .catch((e) => {
        const { message } = e.response.data;
        if (message) {
          setError(message);
        }
        setSubmitting(false);
      });
  };

  const submitForm = (choice: Choice, id?: string) => {
    return id ? updateChoice(Number(id!), choice) : postChoice(choice);
  };

  useEffect(() => {
    if (!isAddMode) {
      // get set form fields
      getChoice(Number(id))
        .then(
          (choice: Choice) => {
            setValue("displayMessage", choice.displayMessage);
            setValue("value", choice.value);
          },

          (error) => {
            history.push("/choices");
          }
        )
        .catch((e) => {
          console.log("error catch");
          console.log(e);
        });
    }
  }, [id, isAddMode, setValue, history]);

  return (
    <div className="container m-1">
      <form
        className={`flex-column justify-content-center`}
        onSubmit={handleSubmit(onSubmit)}
      >
        <h1 className="h3 mb-3 fw-normal">Création d'un choix</h1>
        <CustomInput
          register={register}
          label="Message affiché"
          type="text"
          id="displayMessage"
          error={errors.displayMessage?.message}
          placeholder="Display Message"
        />
        <CustomInput
          register={register}
          label="Valeur du choix"
          type="text"
          id="value"
          error={errors.value?.message}
          placeholder="Choice Value"
        />
        {error && <div className="invalid-feedback d-block">{error}</div>}
        <Link to={"."} className="btn btn-small btn-warning mt-3 mr-2">
          Cancel
        </Link>
        <button
          className="btn btn-small btn-primary mt-3"
          type="submit"
          disabled={submitting}
        >
          {isAddMode ? "Création" : "Mise à jour"}
        </button>
      </form>
    </div>
  );
};

export default NewChoice;

我试图在堆栈和其他网站上查看一点,但无法解决这个 5 天的错误,结果我只得到一个具有适当 id 的空白页面

并且元素应该在这个文件中。

export const CustomInput = ({
  register,
  label,
  type,
  id,
  error,
  placeholder,
}: {
  register: any;
  label: string;
  placeholder: string;
  type: string;
  id: string;
  error?: string;
}) => {
  return (
    <>
      <label htmlFor={id}>{label}</label>
      <div className="form-floating">
        <input
          type={type}
          className="form-control"
          id={id}
          placeholder={placeholder}
          {...register(id)}
        />
        {error && <p className="invalid-feedback d-block">{error}</p>}
      </div>
    </>
  );
};

【问题讨论】:

  • 属性值在哪里?
  • useEffect的编辑模式下我在那里设置值,我的属性是displayMessage, ..
  • 这是来自apichoice.displayMessage
  • 是的,它来自远程 api,我的 api 在一个 nestJs 项目上,我很确定我得到了这个对象。用我的控制器
  • 这些是存储在状态还是其他地方。 ``` setValue("displayMessage",choice.displayMessage); setValue("值", 选择值); ```

标签: reactjs typescript react-tsx


【解决方案1】:

尝试新的状态:

const [isToUpdate, setUpdate] = useState<boolean>(false);

将其添加到 useEffect 数组中:

[id,isToUpdate ....]

在 setValue("value",choice.value); 之后将 setUpdate 添加到要设置值的位置

setUpdate(true);

【讨论】:

  • 它没有改变任何东西
  • 您的输入中也没有 value 属性,所以您是如何处理的。它需要在那里将值放入输入字段。您可以通过在输入标签中给出 value="some temp" 来尝试。
  • 实际上它是用 setValue 方法处理的,我给我的 customInput 提供了 choice.value ,所以应该自动完成
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-04
  • 2017-09-28
  • 1970-01-01
相关资源
最近更新 更多