1、安装依赖
npm i react-redux @reduxjs/toolkit
2、在store/modules文件夹中新建todo.js (billSlice.js)
// 账单列表
import { createSlice } from '@reduxjs/toolkit'
import axios from 'axios'
const billStore = createSlice({
name: 'billStore',
// 数据状态
initialState: {
billList: []
},
reducers: {
// 同步修改方法
setBillList(state, action) {
state.billList = action.payload
}
}
})
// 解构
const { setBillList } = billStore.actions
// 编写异步
const getBillList = () => {
return async (dispatch) => {
// 异步请求
const res = await axios.get('http://localhost:8888/ka')
// 调用同步方法
dispatch(setBillList(res.data))
}
}
export {
getBillList
}
// 导出reducers
const reducer = billStore.reducer
export default reducer
3、在store文件夹中创建index.js,配置上一步创建的todo.js
import { configureStore } from '@reduxjs/toolkit';
import billReducer from './modules/billStore';
const store = configureStore({
reducer: {
bill: billReducer,
},
})
export default store;
4. 在项目根目录的index.js文件中配置启动项
import React from 'react';
import ReactDOM from 'react-dom/client';
import { RouterProvider } from 'react-router-dom'
import { Provider} from 'react-redux'
import store from './store'
import router from '@/router'
// 导入定制样式
import './theme.css'
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<Provider store={store}>
<RouterProvider router={router} >
</RouterProvider>
</Provider>
);
5. 配置完成后,开始使用redux
使用redux的时候有两个不能忘记的钩子函数useSelector,useDispatch;
useSelector是获取store内定义的状态值的钩子函数;
useDispatch是获取store内定义的方法的钩子函数。
import { Outlet } from "react-router-dom";
import { Button } from "antd-mobile";
import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { getBillList } from "@/store/modules/billStore";
const Layout = () =>{
// 获取store方法
const dispatch = useDispatch();
useEffect(()=>{
dispatch(getBillList())
},[dispatch])
// 获取store状态值
const { billList } = useSelector((state) => state.billStore);
console.log(billList)
return (
<div>
<h1>Layout</h1>
<Button color='primary' fill='solid'>
Solid
</Button>
<Outlet />
</div>
)
}
export default Layout;