React 中 useState hook 是什么?

更新日期: 2021-05-13 阅读次数: 299 字数: 266 分类: ReactJS

Ant Design Pro 中经常看到这样的代码,例如 table list 中:

const AdminUsers: React.FC = () => {
  /** 新建窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<API.AdminUser>();
  ...
}

这里面的 useState 是什么意思呢?

useState 的用法

https://reactjs.org/docs/hooks-state.html

官方这个示例非常的简洁明了:

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

useState 是 React 的一个 Hook.

React 为什么要引入 Hook 的概念

Hooks let you split one component into smaller functions based on what pieces are related (such as setting up a subscription or fetching data)

React 觉得 class 的形式非常难以理解,所以想以 Hook 的方式摒弃 class

Hooks let you use more of React’s features without classes

所以,总结起来,Hook 的定义是:

Hooks are functions that let you “hook into” React state and lifecycle features from function components. Hooks don’t work inside classes — they let you use React without classes.

React.FC

React.FC 是 React.FunctionComponent 的缩写。

参考

https://reactjs.org/docs/hooks-state.html

爱评论不评论