npm i react-redux
1.src新建两个文件 globalState.js 全局状态定义 store.js 全局存储定义
2.globalState.js
import { createSlice } from "@reduxjs/toolkit" ; export const globalState = createSlice ( { name: "globalState" , initialState: { data: { } } , reducers: { update : ( state, action ) => { state. data = action. payload; } , } ,
} ) ;
export const { update } = globalState. actions; export default globalState. reducer;
3.store.js
import { configureStore } from '@reduxjs/toolkit'
import globalState from './globalState' export default configureStore ( { reducer: { globalState: globalState}
} )
4.读取状态
import { useSelector, useDispatch } from "react-redux" ;
const state = useSelector ( ( state ) => state. globalState) ;
console. log ( state)
5.存储状态
import { useDispatch } from "react-redux" ;
import { update } from "../../../../state/globalState" ;
dispatch ( update ( { reloadMenu: { id: r. id, reload: c } } ) ) ;