redux里面如何正确的设计reducer?
发布于 8 年前 作者 songyuwen 8152 次浏览 来自 问答

我感觉reducer( state)的设计非常伤脑经,想用combineReducers()来拆分,但是有些全局的变量又在个个子reducer的外部。

比如 我的stateisFetchingisAuthenticated显然是希望全局的,然而我想把userposts单独拿出去用子reducer写,这样一来,在userposts的异步操作中,我就没办法去更改全局的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)

回到顶部