// 导入必要的依赖
import React from 'react';
import { createStore } from 'redux';
import { Provider, useSelector, useDispatch } from 'react-redux';
// 定义初始状态
const initialState = {
count: 0
};
// 定义 reducer 函数
const countReducer = (state = initialState, action) => {
switch (action.type) {
case 'INCREMENT':
return { ...state, count: state.count + 1 };
case 'DECREMENT':
return { ...state, count: state.count - 1 };
default:
return state;
}
};
// 创建 Redux store
const store = createStore(countReducer);
// 定义一个组件来展示状态和派发 actions
const Counter = () => {
const count = useSelector(state => state.count);
const dispatch = useDispatch();
const increment = () => {
dispatch({ type: 'INCREMENT' });
};
const decrement = () => {
dispatch({ type: 'DECREMENT' });
};
return (
<div>
<h1>Count: {count}</h1>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
};
// 使用 Provider 组件将 Redux store 绑定到根组件
const App = () => {
return (
<Provider store={store}>
<Counter />
</Provider>
);
};
export default App;