gpt4 book ai didi

javascript - 更新 redux 商店上的 isLoading 字段

转载 作者:行者123 更新时间:2023-11-29 15:24:37 26 4
gpt4 key购买 nike

我有指示我的应用程序正在加载的微调器。我的应用程序中的许多 reducer 都需要能够将此加载器设置为 true 或 false。

我的假设:该字段需要位于状态树的最顶层。我们称它为 isLoading

问题:Redux reducers 更新它们自己的状态树部分。有哪些方法可以构建我的 reducer 以更新最顶层的 isLoading 字段?

我对 redux-thunk 很熟悉,但在每个 Action 上都派发一个事件似乎有点矫枉过正。但也许我错了,这是正确的做法。此外,我当然有可能错误地设计了我的状态树。

作为引用,我目前正在使用 redux thunk:

export const fetchAssets = () => {
return dispatch => {
request
.get('http://myapi.com/assets')
.set('Accept', 'application/json')
.end(function(err, res){
if (err) {
return dispatch(fetchAssetsFailure(err));
}
dispatch(fetchAssetsSuccess(res.body.data));
});
}
}

最佳答案

Reducers 接收所有分派(dispatch)的操作,因此您希望您的 isLoading reducer 对每个相关操作使用react,而不是其他 reducer 设置此值。显然,您不能使用 action.type,因为您无法预测所有相关操作,而且它会创建一个非常笨重的 reducer。您可以做的是向操作中添加另一个字段,此 reducer 将对该字段使用react。

示例操作创建者:

const createSampleAction = (payload, isLoading) => ({
type: 'SAMPLE_ACTION',
payload,
meta: {
isLoading
}
});

和 reducer :

const isLoadingReducer = (state = false, { meta }) => {
const isLoading = meta && meta.isLoading;

if (isLoading !== undefined) {
return isLoading;
}

return state;
}

如果您对使用元而不是操作类型的 reducer 不满意,您可以创建一个中间件,它将执行相同的属性来分派(dispatch) showLoading/hideLoading 操作,并且 reducer 将对这些操作使用react:

const isLoadingMiddleware = ({ dispatch }) => next => {
next(action);
const isLoading = action.meta && action.meta.isLoading;

if (isLoading !== undefined) {
dispatch(isLoading ? showLoading () : hideLoading());
}
}

关于javascript - 更新 redux 商店上的 isLoading 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40610542/

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