gpt4 book ai didi

javascript - react : How optimize a custom hook that shares data?

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

我有一个与以下类似的自定义 Hook :

import { useEffect, useState } from 'react';

import axios from 'axios';

const myCustomHook = () => {
const [countries, setCountries] = useState([]);
const [isLoading, setLoading] = useState(true);

useEffect(() => {
(async () =>
await axios
.get("MY_API/countries")
.then(response => setCountries(response.data))
.finally(() => setLoading(false)))();
}, []);

return countries;
};

export default myCustomHook;

Hook 效果很好,但我在我的应用程序的三个不同区域使用它,尽管事实上所有国家/地区在任何使用 Hook 的地方都是相同的。

是否有一个好的模式来调用 axios 请求一次而不是三次?

编辑 - 解决后的最终代码

import { useEffect, useState } from 'react';

import axios from 'axios';

let fakeCache = {
alreadyCalled: false,
countries: []
};

const myCustomHook = (forceUpdate = false) => {
const [isLoading, setLoading] = useState(true);

if (!fakeCache.alreadyCalled || forceUpdate) {
fakeCache.alreadyCalled = true;

(async () =>
await axios
.get("MY_API/countries")
.then(response => setCountries(response.data))
.finally(() => setLoading(false)))();
}

return countries;
};

export default myCustomHook;

最佳答案

一个解决方案是引入一个自定义的“缓存层”(在你的钩子(Hook)和 axios 请求之间):

  1. 缓存从第一个成功请求返回的 countries 数据,
  2. 在后续请求中返回相同的缓存数据

有多种实现方法 - 一种可能是定义一个 getCountries() 函数,在单独的模块中实现该缓存逻辑,然后从您的钩子(Hook)中调用该函数:

countries.js

import axios from 'axios';

// Module scoped variable that holds cache data
let cachedData = undefined;

// Example function wraps network request with cacheing layer
export const getCountries = async() => {

// We expect the data for countries to be an array. If cachedData
// is not an array, attempts to populate the cache with data
if (!Array.isArray(cachedData)) {
const response = await axios.get("MY_API/countries");

// Populate the cache with data returned from request
cachedData = response.data;
}

return cachedData;
}

myCustomHook.js

import { useEffect, useState } from 'react';
import { getCountries } from "/countries";

const myCustomHook = () => {
const [countries, setCountries] = useState([]);
const [isLoading, setLoading] = useState(true);

useEffect(() => {

(async() => {
try {
setLoading(true);

// Update hook state with countries data (cached or fresh)
setCountries(await getCountries());

} finally {
setLoading(false)
}
}, []);
});
}
export default myCustomHook;

关于javascript - react : How optimize a custom hook that shares data?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58313364/

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