1. 下载redux
npm install redux || yarn add redux
npm install react-redux || yarn add react-redux
2. 创建存储redux文件夹
redux文件夹中创建store
reducers 文件夹(名字自定义)中的文件是用户存储状态的,自行创建与否,自己视情况而定
3.配置store文件
// createStore 遗弃,改成 legacy_createStore
import { legacy_createStore, combineReducers } from "redux";
//上面创建的文件夹中的文件引入
import { CollapsedReducers } from "./reducers/CollapsedReducers";
import { LoadingReduces } from "./reducers/LoadingReduces";
//数据持久化 官网默认写法
import { persistStore, persistReducer } from "redux-persist";
import storage from "redux-persist/lib/storage";
//
const persistConfig = {
//数据存储
key: "persist", //自定义
storage,
//不设置 默认全部执行reducers中的数据-持久化
blacklist: ["LoadingReducer"], //黑名单 不执行
// whitelist:['LoadingReducer'] 白名单 只执行
};
const reducers = combineReducers({
//使用combineReducers从许多中创建单个根减速器
CollapsedReducers,
LoadingReduces,
});
const persistedReducer = persistReducer(persistConfig, reducers);
const store = legacy_createStore(persistedReducer);
const persistor = persistStore(store);
export { store, persistor };
4.在LoadingReduces和CollapsedReducers进行配置 自行判断是否创建
export const CollapsedReducers = (
prevState = { isCollapsed: false }, //设置默认状态的值
action
) => {
let { type } = action;
switch (type) { //判断值的名称
case "change_collapsed":
let newState = { ...prevState };
newState.isCollapsed = !newState.isCollapsed;
return newState;
default:
return prevState;
}
};
export const LoadingReduces = (prevState = { isCollapsed: false }, action) => {
let { type, payload } = action;
switch (type) {
case "change_loading":
let newState = { ...prevState };
newState.isLoading = payload;
return newState;
default:
return prevState;
}
};
5. 在App.js中配置
import "./App.css";
import IndexRouter from "./router/indexRouter";
import { Provider } from "react-redux"; //引入
import { store, persistor } from "./redux/store";
import { PersistGate } from "redux-persist/integration/react"; //数据持久化
function App() {
return (
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<IndexRouter>{/* <Outlet /> */}</IndexRouter>
</PersistGate>
</Provider>
);
}
export default App;
6.在需要用到状态的xxx.js文件中配置
import { Spin } from "antd"; //antd 中加载中组件
import { connect } from "react-redux"; //redux
需要用到的值的地方引入
通过props去点属性值
/*
文件最下方使用
connect(
//mapStateToProps
//mapDispatchToProps
)(被包装的组件)
*/
const mapStateToProps = ({ LoadingReduces: { isLoading } }) => ({
isLoading,
});
export default connect(mapStateToProps)(NewsRouter);