简体   繁体   中英

React typescript useState string in object type error

Hello god developer friends

I have a Type error problem

Sorry update my question

type

interface IInfo {
  name: string;
  password: string;
}

useState

const [info, setInfo] = useState<IInfo>({
    name: '',
    password: '',
  });

Error code

useEffect(() => {
    setInfo({ name: text }); <- error
    console.log(info);
  }, [text]);

Error message

Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'.

useInput

import React, { useState, useCallback } from 'react';

export default () => {
  const [text, setText] = useState<string>();


  const getText = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      const { value, placeholder } = e.target;
      setText(value);
    },
    [text],
  );
  return { text, getText};
};

Why name is error ?

I know problem is type definition

How defined useState type ?

Your type definition is fine assuming you always want name and password properties on that object.

The problem with your update is that you're only providing name , not name and password , to setInfo . Unlike setState in class components, the setter you get from useState doesn't accept partial updates.

If you want to update name and password separately, you have (at least) two options:

  1. Keep your current state member and use the callback form of the state setter and include the current password in the update:

     setInfo(({password}) => ({ name: text, password }));
  2. Use two separate state members:

     const [name, setName] = useState(""); const [password, setPassword] = useState("");

    Then use setName or setPassword .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM