使用 Hooks 实现 Redux 的功能可以通过 useReducer 和 useContext 来实现。下面是一个简单的示例,演示如何用 Hooks 创建一个基本的 Redux-like 状态管理。
1. 创建 Redux Store
首先,创建一个 reducer 函数来管理状态变化。
// reducer.js
const initialState = {count: 0
};const reducer = (state, action) => {switch (action.type) {case 'INCREMENT':return { ...state, count: state.count + 1 };case 'DECREMENT':return { ...state, count: state.count - 1 };default:return state;}
};export { initialState, reducer };
2. 创建 Context
接下来,创建一个 Context 来提供状态和派发函数。
// StoreContext.js
import React, { createCont