redux的模块拆分
根据独立的模块可以拆分出单独的reducer
合并reducer:redux自带的一个方法combineReducers,将拆分的reducer最后合并成一个大的reducer
redux-thunk:可以在reducer进行异步操作 下载:npm i redux-thunk -S
store/index.js:
import { createStore, combineReducers, applyMiddleware } from 'redux'
import thunkMiddleware from 'redux-thunk'
let data = (state = { searchIpt: '' }, action) => {
switch (action.type) {
case 'SAVE_DATA':
if (action.data !== undefined) {
state.list = action.data.listData
return JSON.parse(JSON.stringify(state))
}
default:
return state
}
}
let loginModule = (state = { isShow: false }, action) => {
switch (action.type) {
case 'LOGIN_CLICK':
if (action.data != undefined) {
state.isShow= action.data
return JSON.parse(JSON.stringify(state))
}
default:
return state;
}
}
const store = createStore(combineReducers({
data, loginModule
}), applyMiddleware(thunkMiddleware))
export default store
组件内使用:
正常情况下dispatch传的是一个对象(同步)
使用redux-thunk以后dispatch可以支持传一个函数进行异步请求
const mapStateToProps = (state) => {
return {
list: state.data.list,
isShow: state.loginModule.isShow
}
}
const mapDispatchToProps = dispatch => {
return {
getData() {
dispatch(() => {
axios.get('/api/getData').then(res => {
if(res.data.code===1){
dispatch({
type: 'SAVE_DATA',
data: res.data.data
})
}else{
console.log(res)
}
})
})
},
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Home);