gpt4 book ai didi

javascript - 避免在 Saga 上不需要的请求

转载 作者:行者123 更新时间:2023-11-30 13:53:12 26 4
gpt4 key购买 nike

我有一个绑定(bind)到“@@router/LOCATION_CHANGE”操作的 redux-saga 函数。主要问题是每次用户在部分之间切换时都会有大量不必要的请求,因为数据已经存在于商店中。

export function* resourcesSwitcher(action) {
yield put(getConstants());

switch (section) {
case '/dashboard':
yield all([
put((check) ? getDate() : addDate(date)),
]);
break;
case '/apps':
yield all([
put(getApps({ filter })),
put(getPlatforms()),
roleId >= C.roles.User && put(getKeys({ filter })),
]);
break;
case '/rules':
yield all([
put(getRules({ filter: rulesFilter })),
put(getKeys({ filter })),
put(getDevices()),
]);
break;
case '/revenues':
yield all([
put((check) ? getDate() : addDate(date)),
put(getApps()),
put(getAccounts()),
]);
break;
case '/keys':
yield all([
put(getKeys({ filter })),
put(getApps()),
]);
break;
default:
}
}

export default function* root() {
yield all([
takeLatest('FETCH', resourcesSwitcher),
]);
}

我想添加一些检查器函数来确保 store[value] 不为空,这样 saga 就可以避免调用。 f.e 如果数据已经存在,则不会在每个 LOCATION_CHANGE 操作上请求常量或应用程序。

const getStore = (state) => state;
const store = yield select(getStore);

function* checker(value) {
console.log('checking store', value);
let result = null;
let method = null;
switch (value) {
case 'apps':
method = getApps();
break;
case 'keys':
method = getKeys();
break;
case 'constants':
method = getConstants();
break;
default:
result = (store[value].data.length) ? null : method;
}
if (result) return yield put(result);
console.log('prefetched, avoided');
return {};
}

我没有完全掌握 redux-saga,所以可能是实现这个“缓存”的更好方法。

最佳答案

对于这种情况,我通常会编写一个选择器,并在调用 api 之前检查它。像这样的东西:

// adapt this selector based on your store structure and conditions
// for fetching data again
const shouldFetchConstantsSelector = state => state.constants.data.length > 0;

export function* resourcesSwitcher(action) {
const shouldFetchConstants = yield select(shouldFetchConstantsSelector);
if (shouldFetchConstants) {
yield put(getConstants());
}
... etc.
}

关于javascript - 避免在 Saga 上不需要的请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57808843/

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