首先 npm install react-redux 和 npm install redux
新建store文件夾再建 index.js文件
/** @format */
import { createStore } from 'redux';
import reducer from './reducer';
const store = createStore(reducer);
export default store;
新建reducer.js 文件
export default (state = '', { type, payload }) => {
switch (type) {
// 登錄,設(shè)置權(quán)限,和登錄態(tài)
case 'LOGIN':
return { ...state, ...payload, isLogin: true, };
// 登出,
case 'LOGOUT':
return { ...state, ...payload,isLogin: false, };
default:
return state;
}
};
在根目錄引用
import { Provider, useDispatch, useSelector } from 'react-redux';
import store from './store/index';
const App = () => {
const dispatch = useDispatch();
//登錄
const login= useCallback(async (val) => {
try{
const { userName, pwd } = val;
// 調(diào)用的登錄接口
const resp = await login({
username: userName,
password: md5(pwd),
});
resp && dispatch({
type: 'LOGIN',
payload: resp,
});
}catch(e){
message.error({ content: e.response.data.message });
}
}, [dispatch,login]);
// 登出
const logout = useCallback(async () => {
// 調(diào)用的登出接口
await fetchLogout();
dispatch({ type: 'LOGOUT' });
}, [dispatch, fetchLogout]);
return (
<Provider store={store}>
{/* 包裹全部組件 */}
<Home/>
</Provider>
);
);
};
然后在Home組件可以通過store.getState()獲取登錄的一些數(shù)據(jù)
import React, { useCallback, useEffect, useState } from "react";
import store from '@src/store';
const Home= () => {
console.log(store.getState())
return (
<>
</>
);
};
export default Home;
用redux 和 localStorage都可以全局存儲(chǔ)數(shù)據(jù)