redux原理图
1、创建store、reducer、action
modules文件夹中是保存的按模块对应的文件,格式保持统一。
authStates如下:
export default {
state: {
name: '',
balance: 0
},
action: {
setName: (state: {name: string}, action: {value: string})=>{
state.name = action.value
},
setBalance: (state: {balance: number}, action: {value: number})=>{
state.balance = action.value
}
}
}
每个文件导出的都包括了两部分,state和action,这样可以动态生成reducer,state用来保存初始值以及数据格式,action是修改state值
动态生成reducer
其中遍历modules文件夹中的ts,webpack和vite使用的方法不一样
webpack使用过的是require,vite中使用的是import.meta.glob
生成store,绑定reducer
import { legacy_createStore, combineReducers, compose, applyMiddleware } from "redux";
import reduxThunk from 'redux-thunk'
//const modulesFiles = require['context']('./modules', true, /\.ts$/); //webpack
const modulesFiles:{} = import.meta.glob('./modules/*.ts', { eager: true })
const reducers = {}
const modules = {}
for (const key in modulesFiles) {
let moduleName = key.replace(/(\.\/module\/|\.ts)/g, '').split('/')[2]
modules[moduleName] = modulesFiles[key]['default']
let reducer = (state = modules[moduleName].state, action: {type: string})=> {
if (modules[moduleName].action[action.type]){
let newState = JSON.parse(JSON.stringify(state));
modules[moduleName].action[action.type](newState, action)
return newState
}
return state;
}
reducers[moduleName] = reducer
}
const combine = combineReducers(reducers)
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : compose
const store = legacy_createStore(combine, composeEnhancers(applyMiddleware(reduxThunk)))
export default store
2、store和组件绑定
import store from './store'
ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
)
3、获取值并且修改值
import { useAppDispatch, useAppSelector } from "../../type"
const Auth = ()=>{
const dispatch = useAppDispatch()
const {name,balance } = useAppSelector((state: RootState)=> {
return {
name: state.authStates.name,
balance: state.authStates.balance
}
})
const changeName = ()=>{
dispatch({type: 'setName', value: 'doris'})
dispatch({type: 'setBalance', value: balance + 200})
}
return <div>name: {name}-{balance}<br></br>
<button onClick={changeName}> change name</button></div>
}
export default Auth
这样一个基本的流程就是OK了,后续有模块新增直接在modules文件夹中添加对应的模块数据即可。
但是我们项目中不仅是简单的这样一个同步使用,我们还有网络请求,数据的异步设置,然后我们就用到中间件redux-thunk,这里同时封装了一个异步的action:
import { getReq, postReq } from "../../api/server/abstract"
const states = {
state: {
},
action: {
asyncLoading: (state: any, action:{value: { loading: boolean, url: string}} ) =>{
state[`${action.value.url}_loading`] = action.value.loading
},
asyncStates: (state, action: {value: {url: string, res: any}})=>{
state[`${action.value.url}`] = action.value.res
},
},
asyncAction: {
getReqAction: (payload: {url: string, params})=>{
return (dispatch) =>{
dispatch({type: 'asyncLoading', value: {url: payload.url, loading: true}})
getReq(payload).then((response)=>{
dispatch({type: 'asyncLoading', value: {url: payload.url, loading: false}})
dispatch({type: 'asyncStates', value: {url: payload.url, res: response}})
})
}
},
postReqAction: (payload: {url: string, data?, params?})=>{
return (dispatch) =>{
dispatch({type: 'asyncLoading', value: {url: payload.url, loading: true}})
postReq(payload).then((response)=>{
dispatch({type: 'asyncLoading', value: {url: payload.url, loading: false}})
dispatch({type: 'asyncStates', value: {url: payload.url, res: response}})
})
}
}
}
}
export default states
其中getReq和postReq是封装的get和post请求,在请求开始之前设置loading为true, 请求结束,设置结果,并将loading置为false
获取数据:
import { memo, useEffect } from "react";
import requestStates from '../../store/modules/requestStates'
import { useAppDispatch, useAppSelector } from "../../type";
const Home = ()=>{
const getUrl = '/collections/all'
const dispatch = useAppDispatch()
const {list, isLoading} = useAppSelector((state: RootState)=>{
return {
list: state.requestStates[getUrl],
isLoading: state.requestStates[`${getUrl}_loading`],
};
})
useEffect(()=>{
dispatch(requestStates.asyncAction.getReqAction({url: getUrl, params: {size: 20}}))
}, [])
return <div>
{isLoading || !list ? <div>加载中</div> : <div>
{list.map((item, index)=>{
return <div key={index}>{item.collection_name}</div>
})}
</div>}
</div>
}
export default memo(Home)
请求的时候,我们只需要变更url的路径就可以了。