前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >React技巧之具有空对象初始值的useState

React技巧之具有空对象初始值的useState

作者头像
chuckQu
发布2022-08-19 15:18:10
1.3K0
发布2022-08-19 15:18:10
举报
文章被收录于专栏:前端F2E

原文链接:https://bobbyhadz.com/blog/react-typescript-usestate-empty-object[1]

作者:Borislav Hadzhiev[2]

正文从这开始~

类型声明useState

要在React中用一个空对象的初始值来类型声明useState钩子,可以使用钩子泛型。比如说:const [employee, setEmployee] = useState<{[key: string]: any}>({})state变量将被类型化为一个具有动态属性和值的对象。

代码语言:javascript
复制
// App.tsx

import {useEffect, useState} from 'react';

const App = () => {
  // 👇️ const employee: {[key: string]: any;}
  const [employee, setEmployee] = useState<{[key: string]: any}>({});

  useEffect(() => {
    setEmployee({
      name: 'Alice',
      salary: 100,
      department: 'Dev',
      tasks: ['dev', 'test', 'ship'],
    });
  }, []);

  return (
    <div>
      <h2>Name: {employee.name}</h2>
      <h2>Salary: {employee.salary}</h2>
    </div>
  );
};

export default App;

{[key: string]: any}TypeScript中的索引签名语法,当我们不清楚一个类型的所有属性名称和值的时候,就可以使用索引签名。

示例中的索引签名意味着,当一个对象的索引是string时,将返回类型为any的值。

当你事先不知道对象的所有属性时,你可以使用这种方法。

你可以尝试用一个索引签名来覆盖一个特定属性的类型。

代码语言:javascript
复制
// App.tsx

import {useEffect, useState} from 'react';

type Employee = {
  [key: string]: any;
  age?: number;
  tasks?: string[];
};

const App = () => {
  // 👇️ const employee: {[key: string]: any;}
  const [employee, setEmployee] = useState<Employee>({});

  useEffect(() => {
    setEmployee({
      name: 'Alice',
      salary: 100,
      department: 'Dev',
      tasks: ['dev', 'test', 'ship'],
    });
  }, []);

  return (
    <div>
      <h2>Name: {employee.name}</h2>
      <h2>Salary: {employee.salary}</h2>
    </div>
  );
};

export default App;

我们将agetasks属性标记为可选,并明确的为它们指定了类型。可选属性既可以拥有undefined值,也可以拥有指定的类型。这就是为什么我们仍然能够将state对象初始化为空对象。

然而,为我们事先知道的属性提供类型是十分有用的,因为agetasks属性只能被设置为指定的类型。

如果对象的属性可以是多个类型,那么就是用联合类型。

代码语言:javascript
复制
import {useEffect, useState} from 'react';

type Employee = {
  [key: string]: any;
  // 👇️ age is number OR string
  age?: number | string;
  tasks?: string[] | number[];
};

const App = () => {
  // 👇️ const employee: {[key: string]: any;}
  const [employee, setEmployee] = useState<Employee>({});

  useEffect(() => {
    setEmployee({
      name: 'Alice',
      salary: 100,
      department: 'Dev',
      tasks: ['dev', 'test', 'ship'],
    });
  }, []);

  return (
    <div>
      <h2>Name: {employee.name}</h2>
      <h2>Salary: {employee.salary}</h2>
    </div>
  );
};

export default App;

我们使用了联合类型来将age属性设置为number类型或者string类型。

你可以重复上述过程,根据实际情况来包括尽可能多的类型。

参考资料

[1]

https://bobbyhadz.com/blog/react-typescript-usestate-empty-object: https://bobbyhadz.com/blog/react-typescript-usestate-empty-object

[2]

Borislav Hadzhiev: https://bobbyhadz.com/about

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2022-05-20,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 前端F2E 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 类型声明useState
    • 参考资料
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档