Redux状态管理

154 阅读1分钟

1、安装redux @reduxjs/toolkit

npm install @reduxjs/toolkit redux -S

2、在src目录下创建store文件夹,创建index.js

import { configureStore } from "@reduxjs/toolkit";
// 导入store实例
import demo from "./modules/demoStore";
const store = configureStore({
    // 挂载redux实例,在jsx中导出变量时需要使用到
    reducer: {
        demo: demo
    }
})
export default store

3、在store文件夹下创建modules文件夹,创建demoStore.js

import { createSlice } from "@reduxjs/toolkit";
// 创建slice实例
const demoStore = createSlice({
    name: 'demo',
    initialState: {
        msg: 'hello'
    },
    reducers: {
        // 定义更新的方法
        setMsg: (state, action) => {
            // action.payload 接收到更新的值(例如:string,object等)
            state.msg = action.payload;
        }
    }
})
// 按需导出方法
export const { setMsg } = demoStore.actions;
const demo = demoStore.reducer;
// 默认导出reudcer实例
export default demo;

4、在App.js中引入store实例

import store from "./store";
import { Provider } from "react-redux";
<Provider store={store}>
    <App/>
</Provider>

5、在Demo组件中引入store实例

import { useSelector, useDispatch } from "react-redux";
// 引入store实例中数据更新的方法
import { setMsg } from "../store/modules/demoStore"
const Demo = () => {
    // 异步更新
    const dispatch = useDispatch();
    // 获取store实例中的数据
    const { msg } = useSelector(state => state.demo);
    // 异步更新数据
    const getMsg = () => {
        return async (dispatch) => {
            const res = await axios.get('http://localhost:3001/msg')
            console.log('res === ', res.data.data)
            // 从接口拿到数据,并更新store实例中的数据
            dispatch(setMsg(res.data.data))
        }
    }
    // 组件加载时,执行异步更新数据
    useEffect(() => {
        // 执行异步
        getMsg(getList())
    }, [dispatch])
    return (
        <div>
            {/* 展示数据 */}
            <h1>{msg}</h1>
            {/* 数据更新,简单同步更新 */}
            <button onClick={() => setMsg('redux')}>set</button>
        </div>
    )
}
export default Demo;