React Hook笔记(3)- useReducer

useReducer是 useState的升级版

使用方法:

  步骤一:定义“修改规则”函数,修改state属性的函数

  步骤二:调用useReducer

const [state, dispatch] = useReducer(reducer, initialArg, init);

    reducer: 修改规则

    initialArg:默认值

     init:针对默认值做修改的方法 -可选

import { useReducer } from "react";
import counter from "../store/counter";

function UseReducerTest(props) {
  const [count, setCcount] = useReducer(counter, 0)
  return (<>
    <div>{count}</div>
    <button onClick={() => setCcount({ type: 'action1' })}>action1</button>
  </>)

}

//根据acton的属性值,对state更新,并返回新的state-----修改规则
function counter(state = 0, action) {
  switch (action.type) {
    case 'action1':
      return state + 1
    case 'action1':
      return state - 1
    default:
      return state
  }
}


export default UseReducerTest


使用场景

 state 逻辑较复杂且包含多个子值,或者下一个 state 依赖于之前的 state


版权声明:本文为u011723406原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。