在Redux Thunk中使用getState是一种很好的做法吗?

spu*_*nge 23 getstate redux redux-thunk

我在其他问题中看到了相互矛盾(或者只是让我感到困惑)关于getState在一个动作中使用是否可接受的答案,而且我已经看过很多次它被称为反模式.对我来说,它似乎工作得很好,但如果我们不使用它,最好的做法是什么getState

getState在一个thunk中使用来过滤当前连接到某些模拟数据并被拉入应用程序状态的用户数组.

这是我的行动代码:

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);
        });
    }
);
Run Code Online (Sandbox Code Playgroud)

而我的减速机:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我的reducer中使用的初始帐户状态只是:

account: {
    initialized: false,
    authenticated: false,
},
Run Code Online (Sandbox Code Playgroud)

accountCheck操作将用户(使用getStatefindByUID函数找到)传递到accountLogInSuccessreducer将其值添加到当前帐户状态的位置Object.assign.

希望不必将用户放在我的应用程序的根目录,然后通过props传递它,在Redux中实现这一点并让用户数据在状态下可用的最佳做法是什么?同样,getState到目前为止,在thunk中使用对我来说很有用,但有没有更好的解决方案,这不被认为是反模式?

mar*_*son 29

我写了一篇名为Idiomatic Redux的博客文章:关于Thunks,Sagas,Abstraction和Reusability的思考,详细讨论了这个主题.在其中,我回应了几个关于thunks和使用的批评getState(包括Dan Abramov 在动作创建者访问Redux状态的评论).事实上,我的帖子特别受到像你这样的问题的启发.

作为TL;我的帖子的DR:我相信thunks是一个在Redux应用程序中使用的完全可行的工具,并鼓励使用它们.虽然在使用thunks和sagas以及getState/select在其中使用时需要注意一些有效的问题,但这些问题不应该让你远离使用thunk.

  • 太好了,将其放入答案中会很好,所以它不是仅链接的答案。 (8认同)
  • 那么在中间件中使用getState是不好的做法吗?这个答案似乎可以回答是否使用thunk是一种好习惯。 (7认同)
  • 不,正如我的博客文章所说,这不是一个坏习惯。 (3认同)
  • 这是一个糟糕的答案,因为内容存在于临时链接中。 (2认同)