reactjs - Memoize 自定义钩子的返回值
问题描述
我有一个像这样的自定义 React 钩子:
export default function useLocations(locationsToMatch) {
const state = useAnotherHookToGetStateFromStore();
const { allStores } = state.locations;
const allLocations = {};
allStores.forEach((store) => {
const { locationId, locationType } = store;
const isLocationPresent = locationsToMatch.indexOf(locationId) !== -1;
if (isLocationPresent && locationType === 'someValue') {
allLocations[locationId] = true;
} else {
allLocations[locationId] = false;
}
});
return allLocations;
}
当我在我的 React 组件中使用上面的钩子时,如下所示:
const locations = useLocations([908, 203, 678]) // pass location ids
由于无限渲染,我得到一个最大调用深度错误。这是因为我的组件中有一些代码使用useEffect
如下钩子:
useEffect(() => { // some code to re-render component on change of locations
}, [locations])
所以我试图将我的返回值包装在useLocations
钩子中,useMemo
如下所示:
export default function useLocations(locationsToMatch) {
const state = useAnotherHookToGetStateFromStore();
const { allStores } = state.locations;
const allLocations = {};
const getStores = () => {
allStores.forEach((store) => {
const { locationId, locationType } = store;
const isLocationPresent = locationsToMatch.indexOf(locationId) !== -1;
if (isLocationPresent && locationType === 'someValue') {
allLocations[locationId] = true;
} else {
allLocations[locationId] = false;
}
});
return allLocations;
};
return useMemo(() => getStores(), [locationsToMatch, state]);
}
但这仍然会导致消费组件的无限重新渲染。那么如何从我的自定义钩子中返回一个记忆值useLocations
以防止无限重新渲染?
解决方案
推荐阅读
- python - 使用 GetSecretValue AWS 机密管理器 API 时出现 InvalidSignatureException
- python - 如何在时间序列数据框中添加新行
- php - 警告:使用未定义的常量 reply_text – 假定为“reply_text”
- r - 如果 2 个特定列 (R) 中有零,则删除行
- javascript - 如何在动态 Antd 表单中默认显示第一项?
- r - R 包和 S4 对象:“无法找到继承的方法”错误
- php - 从另一个页面重定向时,Laravel 中经过身份验证的用户的 PHPUnit 断言
- gradle - “此处不得使用插件 {} 块。如果您需要强制应用插件”究竟是什么?
- reactjs - 在 React 中为页脚创建超链接
- asp.net-core - 在 Blazor WASM 中获取原始 oauth 令牌?