安装使用
npm install @reduxjs/toolkit react-redux
- 创建store
js
// store.js
import { configureStore } from "@reduxjs/toolkit";
// import { configureStore } from "../rtk-nut";
import countReducer from "./counterSlice";
export default configureStore({
reducer: {
counter: countReducer,
},
});
- 创建 Slice
js
import { createSlice } from "@reduxjs/toolkit";
export const counterSlice = createSlice({
name: "counter",
initialState: {
count: 0,
},
reducers: {
increment: (state) => {
state.count++;
},
decrement: (state) => {
state.count -= 1;
},
incrementByAmount: (state, action) => {
console.log(action, "action"); // {type: 'counter/incrementByAmount', payload: 2}
state.count += action.payload;
},
},
});
export const { increment, decrement, incrementByAmount } = counterSlice.actions;
export default counterSlice.reducer;
- 组件中使用
js
import { useReducer, useEffect } from "react";
import store from "../store/rtkStore";
import { increment, decrement, incrementByAmount } from "../store/counterSlice";
export default function ReduxToolkitPage() {
const count = store.getState().counter.count;
const [, forceUpdate] = useReducer((x) => x + 1, 0);
useEffect(() => {
const unlistener = store.subscribe(() => {
forceUpdate();
});
return () => {
unlistener();
};
}, []);
return (
<div>
<h2>ReduxToolkitPage</h2>
<div>{count}</div>
<button
onClick={() => {
store.dispatch(increment());
}}
>
increment
</button>
<button
onClick={() => {
store.dispatch(decrement());
}}
>
decrement
</button>
<button
onClick={() => {
store.dispatch(incrementByAmount(2));
}}
>
incrementByAmount
</button>
</div>
);
}
redux-toolkit原理实现 todo...