# React技巧之将useState作为对象数组

原文链接:https://bobbyhadz.com/blog/react-typescript-usestate-empty-object (opens new window)

作者:Borislav Hadzhiev (opens new window)

正文从这开始~

# 将useState作为对象数组

要在React中用一个对象数组来类型声明useState钩子,可以使用钩子泛型。比如说,const [employees, setEmployees] = useState<{salary: number; name: string}[]>([]) ,state变量可以被初始化为一个空数组,只接受指定类型的对象。

// App.tsx

import {useState} from 'react';

const App = () => {
  // 👇️ const employees: {salary: number;name: string;}[]
  const [employees, setEmployees] = useState<{salary: number; name: string}[]>(
    [],
  );

  return (
    <div>
      <button
        onClick={() =>
          setEmployees(prevEmployees => [
            ...prevEmployees,
            {salary: 100, name: 'Bob'},
          ])
        }
      >
        Add employee
      </button>

      {employees.map((employee, index) => {
        return (
          <div key={index}>
            <h2>
              salary: {employee.salary} / name: {employee.name}
            </h2>
          </div>
        );
      })}
    </div>
  );
};

export default App;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

我们使用泛型来准确的对useState钩子进行类型声明,同时使用空数组来初始化钩子。

react-typescript-usestate-array-of-objects.gif

如果我们不使用泛型,比如说,useState<{salary: number; name: string}[]>([]) ,当对其输入钩子的时候,state变量的类型将会是never[] 。换句话说,就是一个永不包含任何元素的数组。

如果频繁调用useState钩子,你也可以使用类型别名或者接口。

// App.tsx

import {useState} from 'react';

type Employee = {
  salary: number;
  name: string;
};

const App = () => {
  // 👇️ const employees: Employee[]
  const [employees, setEmployees] = useState<Employee[]>([]);

  return (
    <div>
      <button
        onClick={() =>
          setEmployees(prevEmployees => [
            ...prevEmployees,
            {salary: 100, name: 'Bob'},
          ])
        }
      >
        Add employee
      </button>

      {employees.map((employee, index) => {
        return (
          <div key={index}>
            <h2>
              salary: {employee.salary} / name: {employee.name}
            </h2>
          </div>
        );
      })}
    </div>
  );
};

export default App;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

我们将对象类型提取为一个类型别名,并将其作为Employee[]来对useState钩子进行类型声明。

如果我们试图向state数组添加一个不同类型的值,我们会得到一个类型检查错误。

// App.tsx

import {useState} from 'react';

type Employee = {
  salary: number;
  name: string;
};

const App = () => {
  // 👇️ const employees: Employee[]
  const [employees, setEmployees] = useState<Employee[]>([]);

  // ⛔️ Argument of type '(prevEmployees: Employee[]) => (string | Employee)[]' is not assignable to parameter of type 'SetStateAction<Employee[]>'.
  setEmployees(prevEmployees => [...prevEmployees, 'Hello world']);

  return (
    <div>
      <button
        onClick={() =>
          setEmployees(prevEmployees => [
            ...prevEmployees,
            {salary: 100, name: 'Bob'},
          ])
        }
      >
        Add employee
      </button>

      {employees.map((employee, index) => {
        return (
          <div key={index}>
            <h2>
              salary: {employee.salary} / name: {employee.name}
            </h2>
          </div>
        );
      })}
    </div>
  );
};

export default App;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

这个例子向我们展示了,试图向一个类型为Employee[]的state数组添加一个字符串,会导致类型检查器报错。