https://react.dev/reference/react/useReducer
useReducer: 向组件添加一个reducer, 声明一个带有更新逻辑的状态变量。
定义:
const [state, dispatch] = useReducer(reducer, initialArg, init?)
参数:
reducer:reducer 函数(),指定状态如何更新。 它必须是纯粹的,应该以state和action作为参数,并且应该返回下一个状态。 状态和动作可以是任何类型。
initialArg:计算初始状态的值。 它可以是任何类型的值。 如何根据它计算初始状态取决于下一个初始化参数。
可选 init:应返回初始状态的初始化函数。 如果未指定,则初始状态设置为initialArg。 否则,初始状态将设置为调用 init(initialArg) 的结果。
返回值:
useReducer 返回一个恰好包含两个值的数组:
state: 在第一次渲染期间,它被设置为 init(initialArg) 或initialArg(如果没有 init)。
dispatch: 可将状态更新为不同的值并触发重新渲染。
dispatch函数
useReducer 返回的dispatch函数允许将状态更新为不同的值并触发重新渲染。
参数
action:用户执行的操作。 它可以是任何类型的值。 按照惯例,动作通常是一个对象,具有标识它的类型属性,以及可选的具有附加信息的其他属性。
dispatch({ type: 'incremented_age' });
用法
1.reducer将state的更新逻辑封装到函数里,通过action的type参数来判断更新条件,并返回state对象。
useReduce传入reducer函数和state的初始值,并返回更新的state和dispatch.
页面的操作事件调用dispatch函数,传入action的type参数,使reducer找到具体的更新逻辑来更新state.
import React from 'react';
import { useReducer } from 'react';
export function ReducerDemo() {
function reducer(state: any, action: any) {
if (action.type === 'increase') {
return { age: state.age + 1 } //注意:这里返回的是object
}
throw Error('Unknown action.');
}
const [state, dispatch] = useReducer(reducer, { age: 15 });
return <div>
<div onClick={() => dispatch({ type: 'increase' })}>incease age</div>
<div>Hello! You are {state.age}.</div>
</div>
}
useReducer 与 useState 非常相似,但它允许您将状态更新逻辑从事件处理程序移动到组件外部的单个函数中
2.reducer 使用switch
function reducer(state, action) {
switch (action.type) {
case 'incremented_age': {
return {
name: state.name,
age: state.age + 1
};
}
case 'changed_name': {
return {
name: action.nextName,
age: state.age
};
}
}
throw Error('Unknown action: ' + action.type);
}
3.dispatch 传多个参数
function reducer(state: any, action: any) {
if (action.type === 'increase') {
return { age: state.age + 1, name: action.nextName }
}
throw Error('Unknown action.');
}
const [state, dispatch] = useReducer(reducer, { age: 15, name:"lisa" });
dispatch({ type: 'increase', nextName:"Tom" })
初始state使用函数创建
注意:reducer的函数的返回值,使用...state合并所有的状态变量
function reducer(state: any, action: any) {
if (action.type === 'increase') {
return {...state, age: state.age + 1, name: action.nextName,
}
}
}
const [state, dispatch] = useReducer(
reducer,
username,
createInitialState
);
好了,那我们的useReducer到这里就结束了。
宝子们可以收藏评论交流哦