1.安装包
npm install @reduxjs/toolkit react-redux -S
2.看看目录结构
3.store的user代码
import { createSlice } from "@reduxjs/toolkit";
// 初始状态
let initialState = {
count: 1,
users: [
{
name: "zhangzhang",
pass: "123456",
},
],
infor: {
infor_num: 20,
infor_type: "cosplay",
infor_name: "GAT5",
},
};
// 改变状态的方法
let reducers = {
changeCount(state, { payload }) {
state.count = payload;
},
};
// 创建为小仓库
const stateSlice = createSlice({
name: "user",
initialState,
reducers,
});
// 导出改变状态的方法
export const { changeCount } = stateSlice.actions;
// 导出当前整体仓库
export default stateSlice.reducer;
4.store的index代码
// 导入创建库的钩子
import { configureStore } from "@reduxjs/toolkit";
// 引入小仓库
import user from "./user";
// 合为一个大仓库
const store = configureStore({
// 每个reducer代表一个模块的状态管理器
reducer: {
user,
},
});
export default store;
使用
挂到indexjs上
import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { BrowserRouter } from "react-router-dom";
import { Provider } from "react-redux";
import store from "./store";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
// BrowserRouter 是history模式
<BrowserRouter>
{/* // Provider主要配合redux,进行store数据的传递 */}
<Provider store={store}>
<App />
</Provider>
</BrowserRouter>
);
reportWebVitals();
在代码里面进行取值使用方法,pages
// 使用方法的话,用从具体的库引用出来
import { changeCount } from "../../store/user"
// useDispatch是进行方法的使用,useSelector是进行取值
import { useDispatch,useSelector } from "react-redux"
export default function Home() {
const dispatch = useDispatch();
let selector = useSelector(store => store.user.count);
console.log(selector, '==')
// dispatch(changeCount(2))
return (
<div>hello word</div>
)
}