// Action创建函数
function addAction(params){
//返回一个Action对象
return {
type:'add',//add为自定义
...params
}
}
const initState={...}
function reducer(state=initState,action){
return {...}
}
//构建store
import { createstore } from "redux";
//构建store对象
const store = createstore(传递reducer) ;
npm i react-redux
npm i redux
//异步解决方案redux-thunk
npm i redux-thunk
//持久化redux
npm i redux-persist
//创建一个仓储对象,需要reducer作为对象
//本来是这么写的
import { createStore} from 'redux'
//但是改版之后,需要写成下面这个样子
import { legacy_createStore} from 'redux'
//用来管理数据的
const initData={
num :20
}
// state是状态数据的原始值,action={type : "add " ,data:{}
function reducer(state=initData,action){
//!!!!不能操作修改旧的数据
//不能直接修改老的状态数据,应该根据老的状态数据,生成一个新的状态数据,然后返回
const newState=JSON.parse(JSON.stringify(state))
switch(action.type){
case "add1":
newState.num++
break;
case "add2":
newState.num+=action.valbreak;
break;
default:
break;
}
return newState;
}
export default reducer
//创建一个仓储对象,需要reducer作为对象
import {legacy_createStore,applyMiddleware}from ' redux';
import reduxThunk from 'redux-thunk'
import { persistStore, persistReducer } from "redux-persist";//持久化
import storage from "redux-persist/lib/storage";
import reducer from './reducer ';
const persistConfig = {
key: "xxx",
storage: storage,
// whitelist:['LoadingReducers'],//想持久化哪个
};
const persistReducers = persistReducer(persistConfig, reducer )
const store = legacy_createStore(persistReducers, applyMiddleware(reduxThunk))
let persisttore = persistStore(store)
export { store, persisttore }
//这里可能还引入其他东西,为了简洁,我就不写了
...
//状态管理
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
//持久化
import { PersistGate } from "redux-persist/lib/integration/react";
import {store,persisttore} from "@/store";
import App from "./App" ;
ReactDOM.render(
// 将仓储对象传递给根组件
<Provider store={store}>
<PersistGate persistor={persisttore}>
<App />
</PersistGate >
</Provider>,
document.querySelector( "#root")
);
import { useDispatch, useSelector } from "react-redux";
const View = () => {
// 通过useSelector获取仓库数据
const { num } = useSelector((state: { num: any }) => ({ num: state.num }));
// 通过useDispatch修改仓库的数据
const dispatch = useDispatch();
const changeNum = () => {
// dispatch ( {type: '字符串' , val: 1}),val自定义
//同步的写法
dispatch({ type: "add1" });//每点击一次加1
dispatch({ type: "add2" ,val:10});//每点击一次加10
// 异步的写法:dispatch ( 异步执行的函数)
dispatch((dis:Function)=>{
setTimeout(()=>{
dis({ type: "add1" })
},1000)
})
};
return (
<div className="home">
<p>这是Page1页面内容</p>
<p>{num}</p>
<button onClick={changeNum}>按钮</button>
</div>
);
};
export default View;
//index.ts
const store: any = {
state: {
isLoading: false
},
actions: {
//只放同步的方法
add1(newState:{num:number} ,action:{type : string}){
newstate.num++,
}
add2(newstate:{num: number},action:{type: string,val:number}){
newState.num+=action.val,
},
},
asyncActions: {
//react-redux的异步解决方案redux-thunk
//只放异步的方法
//优化redux-thunk的异步写法(模仿vuex的写法)
asyncAdd1(dispatch: Function){
setTimeout(()=>{
dispatch({type: "add1"})
},1000)
},
},
// 名字统一管理
actionNames: {
}
}
//定义一个全局
let actionNames: any = {}
for (let key in store.actions) {
actionNames[key] = key
}
store.actionNames = actionNames
export default store
//reducer.ts
//处理数据
import handle from "./index"
let reducer = (state = { ...handle.state }, action: { type: string}) => {
let newState = JSON.parse(JSON.stringify(state))
for (let key in handle.actionNames) {
if (action.type === handle.actionNames[key]) {
handle.actions[handle.actionNames[key]](newState, action)
break;
}
}
return newState
}
export default reducer
//处理数据
const store ={
state:{
sarr:[10,20,30]
},
actions:{
sarrpush(newState:{sarr:number[},action:{type:string, val:number})(
newstate.sarr.push(action.val)
}
},
asyncActions: {
//只放异步的方法
},
// 名字统一管理
actionNames: {
}
}
//定义一个全局
let actionNames: any = {}
for (let key in store.actions) {
actionNames[key] = key
}
store.actionNames = actionNames
export default store
总结,不同的模块只有state和action里的内容,其他都一样
combineReducers
组合各个模块的reducer//创建一个仓储对象,需要reducer作为对象
import {legacy_createStore,combineReducers,applyMiddleware}from ' redux';
import reduxThunk from 'redux-thunk'
import { persistStore, persistReducer } from "redux-persist";//持久化
import storage from "redux-persist/lib/storage";
import NumStatusrReducer from "./NumStatus/reducer"
import ArrstatusReducer from "./Arrstatus/reducer"
//组合各个模块的reducer
const reducers = combineReducers(i
NumStatusReducer,
ArrstatusReducer
})
const persistConfig = {
key: "xxx",
storage: storage,
// whitelist:['LoadingReducers'],//想持久化哪个
};
const persistReducers = persistReducer(persistConfig, reducers)
const store = legacy_createStore(persistReducers, applyMiddleware(reduxThunk))
let persisttore = persistStore(store)
export { store, persisttore }
// 通过useSelector获取仓库数据
const { num } = useSelector((state: { num: any }) => ({ num: state.NumStatusReducer.num }));
总结
dispatch("add3")
即可 actions: {
add1(newState:{num:number} ,action:{type : string}){
newstate.num++,
}
add2(newstate:{num: number},action:{type: string,val:number}){
newState.num+=action.val,
},
add3(){
....
}
},
dispatch(调用状态管理中的asyncAddx),即dispatch(state.NumStatusReducer.asyncAdd2)
asyncActions: {
asyncAdd1(dispatch: Function){
setTimeout(()=>{
dispatch({type: "add1"})
},1000)
},
asyncAdd2(){}
},
```