使用带有钩子的React.memo来控制输入

时间:2019-05-27 03:29:32

标签: javascript html reactjs react-hooks

我正在通过自定义的React钩子提供一些表单功能。该挂钩具有与Formik类似的功能(但这确实是基本的东西)。

function useFormValidation(initialState, validate) {
  const [values, setValues] = React.useState(initialState);
  const [errors, setErrors] = React.useState({});
  const [isSubmitting, setSubmitting] = React.useState(false);

  React.useEffect(() => {
    if (isSubmitting) {
      const noErrors = Object.keys(errors).length === 0;
      if (noErrors) {
        console.log("authenticated!", values.email, values.password);
        setSubmitting(false);
      } else {
        setSubmitting(false);
      }
    }
  }, [errors]);

  function handleChange(event) {
    setValues({
      ...values,
      [event.target.name]: event.target.value
    });
  }

  function handleBlur() {
    const validationErrors = validate(values);
    setErrors(validationErrors);
  }

  function handleSubmit(event) {
    event.preventDefault();
    const validationErrors = validate(values);
    setErrors(validationErrors);
    setSubmitting(true);
  }

  return {
    handleSubmit,
    handleChange,
    handleBlur,
    values,
    errors,
    isSubmitting
  };
}



表单如下:

function Register() {
  const {
    handleSubmit,

    handleChange,
    handleBlur,
    values,
    errors,
    isSubmitting
  } = useFormValidation(INITIAL_STATE, validateAuth);
  // const [email, setEmail] = React.useState("");
  // const [password, setPassword] = React.useState("");

  return (
    <div className="container">
      <h1>Register Here</h1>
      <form onSubmit={handleSubmit}>
        <Input
          handleChange={handleChange}
          handleBlur={handleBlur}
          name="email"
          value={values.email}
          className={errors.email && "error-input"}
          autoComplete="off"
          placeholder="Your email address"
        />
        {errors.email && <p className="error-text">{errors.email}</p>}
        <Input
          handleChange={handleChange}
          handleBlur={handleBlur}
          value={values.password}
          className={errors.password && "error-input"}
          name="password"
          // type="password"
          placeholder="Choose a safe password"
        />
        {errors.password && <p className="error-text">{errors.password}</p>}
        <div>
          <button disabled={isSubmitting} type="submit">
            Submit
          </button>
        </div>
      </form>
    </div>
  );
}

下一个要记忆的部分是

function Input({
  handleChange,
  handleBlur,
  name,
  value,
  className,
  autoComplete,
  placeholder,
  type
}) {

  return (
    <input
      onChange={handleChange}
      onBlur={handleBlur}
      name={name}
      value={value}
      className={className}
      autoComplete={autoComplete}
      placeholder={placeholder}
      type={type}
    />
  );
}

function areEqual(prevProps, nextProps) {
  console.log(`
    prevProps: ${JSON.stringify(prevProps.value)}
    nextProps: ${JSON.stringify(nextProps.value)}
  `);
  return prevProps.value === nextProps.value;
}
const useMemo = (component, propsAreEqual) => {
  return memo(component, propsAreEqual);
};
export default useMemo(Input, areEqual);

我在第一个输入中输入了一些文本。然后,当我切换到第二个Input并开始键入时,第一个Input失去了值。就像表单没有呈现LAST MEMOIZED输入,而是呈现以前的版本。 我是React的初学者,无法解决问题。有什么帮助吗?

2 个答案:

答案 0 :(得分:2)

尝试使用具有功能的setState更新程序形式:

function handleChange(event) {
  // event.target wont be available when fn is run in setState
  // so we save them in our own local variables here
  const { name, value } = event.target;

  setValues(prev => ({
    ...prev,
    [name]: value
  }));
}

答案 1 :(得分:0)

您的areEqual方法转换为

  

仅在value更改时重新渲染输入。

但是实际上,您的handleChange功能在变化。另外,两个输入都使用相同的handleChange。因此,Input仅“记住”自上次handleChange更改以来的value,并且由于handleChange正在通过闭合跟踪values,因此它依次values创建时会“记住”。

更改areEqual方法(或完全省略)以验证handleChange中的更改将解决您的问题。

function areEqual(prevProps, nextProps) {
  return (
    prevProps.value === nextProps.value &&
    prevProps.handleChange === nextProps.handleChange
  );
}

解决方案here的代码框