gpt4 book ai didi

javascript - 渲染顺序中的 Thunk

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:53:40 26 4
gpt4 key购买 nike

我有一个应用程序可以在渲染时获取一些用户信息。因此,当应用程序首次启动时,它会使用 getUserInformation() 函数获取数据。用户无需手动登录,应用在公司内网。

export function getUserInformation() {
return function (dispatch) {
getUser()
.then((data) => {
dispatch(
{type: GET_USER_SUCCESS, response: data}
)
})
.catch((error) => {
dispatch(
{type: GET_USER_FAILURE, response: error}
)
})
}
}

现在我想获取应用程序的版本以在整个应用程序中可用。但是 API 调用只能在用户登录后触发(因此 getUser() 被成功调用)。我应该只添加

.then(getVersion())

在 getUserInformation() 操作中?它看起来不干净,但我不知道如何以不同的方式处理它。

最佳答案

Action creator 是按顺序分发 action 的合适位置。文档 covers this :

Using an async middleware like Redux Thunk certainly enables scenarios such as dispatching multiple distinct but related actions in a row, dispatching actions to represent progression of an AJAX request, dispatching actions conditionally based on state, or even dispatching an action and checking the updated state immediately afterwards.

如果用户信息和版本 Action 需要单独测试(它们应该位于不同的模块)或单独使用,可以合并 Action 创建者。这需要返回 promises 来链接它们。这也显示了 redux-thunk 的局限性:

function getUserInformation() {
return async (dispatch) => {
try {
dispatch(
{type: GET_USER_SUCCESS, response: await getUser()}
)
} catch (error) {
dispatch(
{type: GET_USER_FAILURE, response: error}
)
}
};
}

...

function getVersion() {
return async (dispatch) => {...};
}

...

function getInitialData() {
return async (dispatch, getState) => {
await getUserInformation()(dispatch);
// we need to use getState to check if there was an error
// because getUserInformation returns a fulfilled promise any way
await getVersion()(dispatch);
};
}

getUserInformation 中重新抛出一个错误是有意义的,但是如果它与 getInitialData 分开使用会很糟糕,因为这会导致未处理的拒绝.更糟糕的是,检查 getState() 是否有错误。

这个场景需要一个比 redux-thunk 更复杂的中间件 dead simple - 可能是基于它并能够处理拒绝的自定义中间件。

关于javascript - 渲染顺序中的 Thunk,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53407207/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com