要使接收所有3个值的useReducer文档示例正常工作,需要做以下几步:
下面是一个示例代码:
import React, { useReducer } from 'react';
// 定义初始状态
const initialState = {
value1: 0,
value2: 0,
value3: 0
};
// 定义action类型
const actionTypes = {
UPDATE_VALUE_1: 'UPDATE_VALUE_1',
UPDATE_VALUE_2: 'UPDATE_VALUE_2',
UPDATE_VALUE_3: 'UPDATE_VALUE_3'
};
// 编写reducer函数
const reducer = (state, action) => {
switch (action.type) {
case actionTypes.UPDATE_VALUE_1:
return { ...state, value1: action.payload };
case actionTypes.UPDATE_VALUE_2:
return { ...state, value2: action.payload };
case actionTypes.UPDATE_VALUE_3:
return { ...state, value3: action.payload };
default:
return state;
}
};
const ExampleComponent = () => {
// 使用useReducer
const [state, dispatch] = useReducer(reducer, initialState);
// 更新状态
const updateValue1 = () => {
dispatch({ type: actionTypes.UPDATE_VALUE_1, payload: 1 });
};
const updateValue2 = () => {
dispatch({ type: actionTypes.UPDATE_VALUE_2, payload: 2 });
};
const updateValue3 = () => {
dispatch({ type: actionTypes.UPDATE_VALUE_3, payload: 3 });
};
return (
<div>
<p>Value 1: {state.value1}</p>
<p>Value 2: {state.value2}</p>
<p>Value 3: {state.value3}</p>
<button onClick={updateValue1}>Update Value 1</button>
<button onClick={updateValue2}>Update Value 2</button>
<button onClick={updateValue3}>Update Value 3</button>
</div>
);
};
export default ExampleComponent;
这样,当点击对应的按钮时,会触发相应的action,并更新相应的值。可以根据实际需求,修改payload的值和更新逻辑。
领取专属 10元无门槛券
手把手带您无忧上云