减速器
// src/reducers/FooReducer.js
export function FooReducer(state, action) {
switch (action.type) {
case 'update': {
return action.newState;
}
// ... other actions
default:
throw new Error('Unknown action type');
}
}
零件
// src/components/BarComponent.js
export function BarComponent() {
const [state, dispatch] = useReducer(FooReducer, []);
return (
{state.map((item) => (<div />))}
);
}
测试
// src/components/BarComponent.test.js
it('should render as many divs as there are items', () => {
act(() => {
const { result } = renderHook(() => useReducer(FooReducer, [1]));
const [, dispatch] = result.current;
wrapper = mount(<BarComponent />);
dispatch({type: 'update', newState: [1, 2, 3]});
});
expect(wrapper.find(div)).toHaveLength(3);
});
上面的测试示例不起作用,但用于演示我想要实现的目标。并且实际上会呈现 0 div,因为组件中声明的初始状态包含 0 个项目。
为了测试目的,我将如何修改减速器的状态或更改它部署的初始状态?
我习惯于在多个组件中使用 Redux 减速器,但是 useReducer 需要一个传递的 initialState ......这引发了一个问题:react-hook 的减速器是否可以通过多个组件作为单个实例使用,还是始终是 2 个单独的实例?