7

React useState Hook 指南

 3 years ago
source link: https://yazhen.me/_posts/2021/React-useState/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

使用 useState

  1. useState(initialValue)
  2. [state, setState] = useState(initialValue)
  3. setState(newState)
  4. setState(prev => next) 可以基于先前的状态来设置新的状态

延迟初始化 state

useState 可以接受一个函数

useState(function initialState() {})

initialState 函数只在初始化渲染的时候执行一次 ,以后的组件渲染中不会再执行。

当初始状态开销比较大的时候,延迟初始化很方便

闭包-状态过时问题

const handleClickAsync = () => {
    setTimeout(function delay() {
      setCount(count + 1);
    }, 3000);
  }

这个 count 就不是正确的值

ES9 新特性(ES2018)

  • Promise.finally()

    一个Promise调用链要么成功到达最后一个.then(),要么失败触发 .catch() 无论运行成功还是失败都会执行

  • Rest / Spread

    三个点(...) ES6 也有三个点操作不过仅限于数组,现在对象中也可以使用

ES10 新特性 (ES2019)

  • 新的基本类型 BigInt
  • 新增了Array的flat()方法和flatMap()方法

在ES10 之后 JS的基本类型将有 7种

七种基本数据类型,分别是: String、Number、Boolean、Null、Undefined、Symbol、BigInt

ES 新特性项目中暂时可能用不上,但是学习有助于了解趋势,以及JS语言在慢慢的完善,越来越强大。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK