简体   繁体   English

TypeScript/React 如何使用 object 类型设置状态类型数组?

[英]TypeScript/React how to setState type array with type object?

just recently started learning TypeScript and started to refactor my old React courses.最近刚开始学习 TypeScript 并开始重构我的旧 React 课程。 Now following problem I encountered:现在我遇到以下问题:

import { useState } from "react";

interface User {
  id: string;
  firstName: string;
  email: string;
  age: number;
} 
interface Users {
  user: User;
  users: User[];
}

const MultipleInputs = () => {
  const [user, setUser] = useState({
    firstName: "",
    email: "",
    age: 0,
  });
  const [users, setUsers] = useState<User[]>([]);

  const handleChange = (e: React.ChangeEvent) => {
    const name = (e.target as HTMLInputElement).name;
    const value = (e.target as HTMLInputElement).value;
    setUser({ ...user, [name]: value });
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (user.firstName && user.email && user.age) {
      const newPerson = { ...user, id: new Date().getTime().toString() };
      setUsers([...user, newPerson]); ❌
    }
  };

Error:错误:

ERROR in 2-multiple-inputs.tsx:32:20
TS2461: Type '{ firstName: string; email: string; age: number; }' is not an array type.
    30 |     if (user.firstName && user.email && user.age) {
    31 |       const newPerson = { ...user, id: new Date().getTime().toString() };     
  > 32 |       setUsers([...user, newPerson]);
       |                    ^^^^
    33 |     }
    34 |   };

Did I miss something obvious or is there a different approach?我错过了一些明显的东西还是有不同的方法?

Thanks in advance.提前致谢。

There is a typo, in line 32 that should be users not user.第 32 行有一个错字,应该是用户而不是用户。

 setUsers([...users, newPerson]);

rest looks good, also if you want to push any item at the end of the array, simply use the push() method, no need to use the array restructuring. rest 看起来不错,如果你想在数组末尾推送任何项目,只需使用push()方法,无需使用数组重组。 Like -喜欢 -

users.push(newPerson)
setUsers(users);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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