需要在react中注入store,一般是在App根组件中,注入方式是 store={store}
import store from './store/index'
<Provider store={store}>
<App />
</Provider>
src\store\counter
// src\store\counter\index.jsx
export const counterReducer = (state = { counter: 0 }, action) => {
if (action.type === 'increment') {
return { counter: state.counter + 1 };
}
if (action.type === 'decrement') {
return { counter: state.counter - 1 };
}
if (action.type === 'reset' && action.name === 'counterReducer') {
return { counter: 0 };
}
return state;
};
src\store\index.jsx
createStore 官方已经不建议使用,所以改成了使用configureStore,需要下载才可以使用
npm install --save @reduxjs/toolkit
// import { createStore } from "redux";
import { configureStore } from '@reduxjs/toolkit';
import reducer from './reducer';
// 引入总模块
const store = configureStore({ reducer });
export default store;
src\store\reducer.jsx
// src\store\reducer.jsx
import { combineReducers } from "redux";
import { counterReducer } from "./counter/index";
// 模块化
const reducer = combineReducers({
Num: counterReducer,
});
export default reducer;
src\pages\reduxTest\index.jsx
import { Button } from "antd";
import { useSelector, useDispatch } from "react-redux";
const Counter = () => {
const dispatch = useDispatch();
const counter = useSelector((state) => { return state.Num.counter });
const incrementHandler = () => {
dispatch({ type: "increment", name: "counterReducer" });
};
const decrementHandler = () => {
dispatch({ type: "decrement", name: "counterReducer" });
};
const toggleCounterHandler = () => {
dispatch({ type: "reset", name: "counterReducer" })
};
return (
<main >
<h1>Redux Counter</h1>
<div>{counter}</div>
<Button type="primary" onClick={incrementHandler}>加1</Button>
<Button type="primary" onClick={decrementHandler}>减1</Button>
<Button type="primary" onClick={toggleCounterHandler}>Toggle Counter</Button>
</main>
);
};
export default Counter;
不记得这个代码参考了谁的了,如有雷同,求放过/(ㄒoㄒ)/~~