我曾在这里的其他问题中看到了关于是否可以在操作内部使用
我在一个thunk中使用
这是我的操作代码:
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);
});
}
);
而我的Reducer:
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
将其值添加到当前账户状态中。
在Redux中,不想通过props从应用程序的根组件获取用户并传递下去,有什么最佳实践方法可以在状态中使用用户数据?目前,在thunk中使用getState
对我来说已经很好了,但是是否有更好的解决方案,而又不被认为是反模式呢?
getState
是thunk API的标准部分。如果它不应该被使用,那么它就不会存在 :) - markerikson