redux里面如何正确的设计reducer?
我感觉reducer( state)的设计非常伤脑经,想用combineReducers()
来拆分,但是有些全局的变量又在个个子reducer
的外部。
比如 我的state
中isFetching
和isAuthenticated
显然是希望全局的,然而我想把user
和posts
单独拿出去用子reducer
写,这样一来,在user
和posts
的异步操作中,我就没办法去更改全局的isFetching
变量了?
const initState = {
isFetching: false,
isAuthenticated: false,
user: {
},
posts: []
}
问的不是很好,大致就是这么个意思。
2 回复
能修改呀,你直接执行一个action呗
// reducer
// global, type: [USER_REQUEST, USER_SUCCESS, USER_FAILURE, BALABALA]
globalState = {
isFetch: false,
isAuthenticated: false
}
type === USER_REQUEST, isFetch => true
type === USER_SUCCESS, isFetch => false, isAuthenticated => true
type === USER_FAILURE, isFetch => false, isAuthenticated => false
// user, type: [USER_REQUEST, USER_SUCCESS, USER_FAILURE, BALABALA]
userState = {}
type === USER_REQUEST, balabala
type === USER_SUCCESS, balabala
type === USER_FAILURE, balabala
// action
// user
function userRequest() {
return { type: USER_REQUEST }
}
function userSuccess(user) {
return {
type: USER_SUCCESS,
user: user
}
}
function userFailure(err) {
return {
type: USER_FAILURE,
error: err
}
}
function userAuth() {
return (dispitch) => {
Promise.resolve().then(function () {
return dispatch(userRequest());
}).then (function () {
// request
}).then(function (res) {
// balabala;
return dispatch(userSuccess(res.user));
}).catch(function (err) {
return dispatch(userFailure(err));
});
}
}
把统一的变量放到common里,通过一个action来变更(比如updateAppInfo)