React在v16.8.0推出了Hooks API,是函数组件也能模拟生命周期进行一些操作。这里对一些常用的hooks API做了下整理:
useState
注*:
! 不可局部更新(对应类组件setState的shallow merge)
! setN(obj)如果obj地址不变,则react就认为obj没变,不更新
! useState可以接收函数,useState( () => { return initialState } )
,该函数返回初始state,只执行一次
! setN也可以接收函数,setN( i => i+1 )
(推荐使用)
简易useState实现沙盒
useReducer
使用步骤:
①创建初始值initial
②创建所有操作reducer(state, action)
③传给useReducer,得到读/写API
④调用写({type: ‘操作类型’})
例:以+1为例
import React, {
useReducer } from "react";
import ReactDOM from "react-dom";
// 创建初始值initial
const initial = {
n: 0 };
// 创建所有操作reducer(state, action)
const reducer = (state, action) => {
if (action.type === "add") {
return {
n: state.n + action.number };
} else {
throw new Error(