Skip to content

九、useReducer

在React的函数组件中,我们可以通过useState()来创建state。这种创建state的方式会给我们返回两个东西state和setState()。state用来读取数据,而setState()用来设置修改数据。但是这种方式也存在着一些不足,因为所有的修改state的方式都必须通过setState()来进行,如果遇到一些复杂度比较高的state时,这种方式似乎就变得不是那么的优雅。

遇到有多种方式修改state的state时,推荐使用useReducer

使用:

  1. 引入

    js
    import {useReducer} from "react";
  2. 定义

    js
    const [state, dispatch] = useReducer(reducer, initialArg, init);
  3. 解释:

    1. state:用来获取state的值
    2. dispatch:可以传参来指定怎么修改state方式
    3. reducer:有俩个参数,第一个参数是state,是state的值,第二个是action,通常用switch来接受dispatch传过来的参数来进行选择修改方式。
    4. initialArg:state的初始值
    5. init:可选。是函数,处理初始state的值

使用方式:

js
import {useReducer, useState} from 'react';
const reducer = (state, action) => {
    switch(action.type){
        case 'add':
            return state + 1;
        case 'sub':
            return state - 1;
    }
};

function App() {
    const [count, countDispath] = useReducer(reducer,1);
    return (
        <div className="App">
            {count}

            <div>
                <button onClick={()=>countDispath({type:'sub'})}>-</button>
                <button onClick={()=>countDispath({type:'add'})}>+</button>
            </div>
        </div>
    );
}

export default App;