目录
一、安装
二、配置
2.创建文件② src/app/features/xxxx/xxxx.js
三、使用
1.新建文件src/pages/Test/index.jsx
安装
npm i @reduxjs/tookit react-redux
配置
1.创建文件① src/app/store.js
a.随便你创建在哪 [ 个人开发的话你开心就好 ]
import { configureStore } from "@reduxjs/toolkit";
import counterReducer from "../features/counter/counterSlice";
export default configureStore({
reducer: counterReducer,
});
2.创建文件② src/features/xxxx/xxxx.js
a.默认值可以写在组件当中
b.个人喜欢分开写如果你不想这么写也可以在app文件下直接创建xxxx.js
c.异步处理函数需要利用使用高阶函数进行middleware的操作
d.同步方法直接在createSlice当中的reducers写入即可
import { createSlice } from "@reduxjs/toolkit";
export const counterSlice = createSlice({
name: "counter",
initialState: {
value: 0,
},
reducers: {
increment: (state) => {
state.value += 1;
},
decrement: (state) => {
state.value -= 1;
},
increamentByAmount: (state, action) => {
console.log(state, action);
state.value += action.payload;
},
},
});
// 默认值
export const initState = (state) => state;
// reducer
export const { increment, decrement, increamentByAmount } =
counterSlice.actions;
// 异步处理函数
export const increamentAsync = (value) => (dispatch) => {
setTimeout(() => {
dispatch(increamentByAmount(value));
}, 3000);
};
export default counterSlice.reducer;
3.编辑文件 index.js
a.好了,基本上我们都已经配置好了,我们需要让react知道你配置了redux
b.找到你的根 [ 滑稽 ] 在App外层包一个react-redux的Provider并设定好store
import {Provider} from "react-redux"
import store from "./app/store"
···
root.render(
<Provider store={store}>
<App/>
</Provider>
)
使用
1.新建文件src/pages/Test/index.jsx
注①:这只是最简单的使用,有其他操作的可以自行更改
注②:useSelector & useDispatch 在这里不过多介绍自行 See Doc
import { useDispatch, useSelector } from "react-redux";
// 引入方法
import {
initState,
increment,
decrement,
increamentByAmount,
increamentAsync,
} from "./features/counter/counterSlice";
function Test() {
// 获取全局状态 【 initState 也可以写成 callback形式 (xxx)=>xxx 】
const Globle = useSelector(initState);
// 实例化useDispatch
const dispatch = useDispatch();
// 解构Cloble对象当中的value值
const {value} = Globle
// 按钮onClick方法
const operation = (type) => {
switch (type) {
case "add": // 全局同步 +1
dispatch(increment());
break;
case "sub": // 全局同步 -1
dispatch(decrement());
break;
case "addnum": // 全局同步 +20
dispatch(increamentByAmount(20));
break;
case "asyncadd": // 全局异步 +30
dispatch(increamentAsync(30));
break;
default:
console.log("参数错误");
}
};
return (
<div className="App">
当前值:{value}
<hr />
<button onClick={() => operation("add")}>加</button>
<button onClick={() => operation("sub")}>减</button>
<button onClick={() => operation("addnum")}>加</button>
<button onClick={() => operation("asyncadd")}>异步加</button>
</div>
);
}
export default Test;