【发布时间】:2017-08-31 23:52:27
【问题描述】:
我在这里的其他问题中看到了相互矛盾的(或者只是让我感到困惑)的答案,关于在操作中使用 getState 是否可以接受,我已经看到很多次它被称为反模式.对我来说,它似乎工作得很好,但如果我们不使用getState,这样做的最佳做法是什么?
我在 thunk 中使用 getState 来过滤当前连接到一些模拟数据并被拉入应用程序状态的用户数组。
这是我的操作代码:
export const accountLogInSuccess = user => ({
type: types.ACCOUNT_LOG_IN_SUCCESS,
user,
});
export const accountLogOutSuccess = () => ({
type: types.ACCOUNT_LOG_OUT_SUCCESS,
});
export const accountCheckSuccess = () => ({
type: types.ACCOUNT_CHECK_SUCCESS,
});
export const accountCheck = () => (
(dispatch, getState) => {
dispatch(ajaxCallBegin());
return apiAccount.accountCheck().then((account) => {
if (account) {
const user = findByUID(getState().users, account.uid);
dispatch(accountLogInSuccess(user));
toastr.success(`Welcome ${user.nameFirst}!`);
} else {
dispatch(accountLogOutSuccess());
}
dispatch(accountCheckSuccess());
}).catch((error) => {
dispatch(ajaxCallError(error));
toastr.error(error.message);
throw (error);
});
}
);
还有我的减速机:
export default function reducerAccount(state = initial.account, action) {
switch (action.type) {
case types.ACCOUNT_LOG_IN_SUCCESS:
return Object.assign({}, state, action.user, {
authenticated: true,
});
case types.ACCOUNT_LOG_OUT_SUCCESS:
return Object.assign({}, {
authenticated: false,
});
case types.ACCOUNT_CHECK_SUCCESS:
return Object.assign({}, state, {
initialized: true,
});
default:
return state;
}
}
我的reducer中使用的账户初始状态只是:
account: {
initialized: false,
authenticated: false,
},
accountCheck 操作将用户(使用getState 和findByUID 函数找到)传递到accountLogInSuccess,其中reducer 通过Object.assign 将其值添加到当前帐户状态。
宁愿不必在我的应用程序的根目录下获取用户,然后通过 props 将其向下传递,在 Redux 中完成此操作并让用户数据在状态下可用的最佳实践是什么?同样,到目前为止,在 thunk 中使用 getState 对我来说效果很好,但是是否有更好的解决方案不被视为反模式?
【问题讨论】:
标签: redux redux-thunk getstate