【问题标题】:Is using getState in a Redux Thunk good practice?在 Redux Thunk 中使用 getState 是一种很好的做法吗?
【发布时间】: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 操作将用户(使用getStatefindByUID 函数找到)传递到accountLogInSuccess,其中reducer 通过Object.assign 将其值添加到当前帐户状态。

宁愿不必在我的应用程序的根目录下获取用户,然后通过 props 将其向下传递,在 Redux 中完成此操作并让用户数据在状态下可用的最佳实践是什么?同样,到目前为止,在 thunk 中使用 getState 对我来说效果很好,但是是否有更好的解决方案不被视为反模式?

【问题讨论】:

    标签: redux redux-thunk getstate


    【解决方案1】:

    我写了一篇名为Idiomatic Redux: Thoughts on Thunks, Sagas, Abstraction, and Reusability 的扩展博客文章,详细讨论了这个主题。在其中,我回应了对 thunk 和getState 使用的一些批评(包括Accessing Redux state in an action creator? 中的 Dan Abramov 的 cmets)。事实上,我的帖子特别受到了像你这样的问题的启发。

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

    【讨论】:

    • 那么在中间件中使用 getState 是不好的做法吗?这个答案似乎回答了使用 thunk 是否是一种好习惯。
    • 不,正如我的博文所说,这不是一个坏习惯。
    • 酷,最好把它放在答案中,所以它不是一个仅链接的答案。
    • 这是一个糟糕的答案,因为内容存在于临时链接中。
    猜你喜欢
    • 2018-06-03
    • 2021-10-04
    • 2018-01-31
    • 2018-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-03
    • 1970-01-01
    相关资源
    最近更新 更多