在同一参数下从同一 API 返回响应后,如何避免重新访问 API
我如何将 useMemo 钩子(Hook)与 axios 部分一起使用以获得更好的性能,因为我是 react 新手,并且确实研究过 useMemo 可用于性能优化。
编辑:
带有备忘录功能的代码现在这是正确的方法吗?
const initialState = {
SwichManagment: [],
Error: false
}
const reducer = (state, action) => {
switch (action.type) {
case "FETCHREQUEST":
return {
...state,
hasError: false
};
case "FETCHSUCCESS":
return {
...state,
SwichManagment: action.payload,
};
case "FETCHFAILURE":
return {
hasError: true
};
default:
return state;
}
}
const SwitchManagment = ({ IdentifierId }) => {
const [states, dispatch] = useReducer(reducer, initialState)
const memo = (callback) => {
const cache = new Map();
return (...args) => {
const selector = JSON.stringify(args);
if (cache.has(selector)) return cache.get(selector);
const value = callback(...args);
cache.set(selector, value);
return value;
};
};
const memoizedAxiosGet = memo(axios.get);
useEffect(() => {
dispatch({
type: "FETCHREQUEST"
});
memoizedAxiosGet(`https://example.com/${IdentifierId}/now`)
.then(reponse => {
dispatch({
type: "FETCHSUCCESS",
payload: response.data
});
})
.catch(error => {
dispatch({
type: "FETCHFAILURE"
});
});
}, [IdentifierId]);
return (
<div >
{Object.keys(states.SwitchManagment).map(key => (
<div className="item" key={states.SwitchManagment[key].id}>
<p>{states.SwitchManagment[key].name}</p>
<p>
{states.SwitchManagment[key].progress}
</p>
</div>
))}
</div>
);
};
最佳答案
React.useMemo
不保存以前结果中的值。查看this example at dev.to :
const value = useMemo(() => expensiveFunction(a), [a]);
When it already did the calculation for
a
being2
, then it won't do it for2
next time. Likewise for the3
or4
.However, it really can only memoize one value. If the first time, it did the calculation for
1
, and next it did the calculation for2
, it won't remember what the result is for1
any more. When supplied with1
again, it will do the calculation again.
所以在你的情况下,你应该创建一个
memo
长内存功能:const memo = (callback) => {
// We will save the key-value pairs in the following variable. It will be our cache storage
const cache = new Map();
return (...args) => {
// The key will be used to identify the different arguments combination. Same arguments means same key
const key = JSON.stringify(args);
// If the cache storage has the key we are looking for, return the previously stored value
if (cache.has(key)) return cache.get(key);
// If the key is new, call the function (in your case axios.get)
const value = callback(...args);
// And save the new key-value pair to the cache
cache.set(key, value);
return value;
};
};
const memoizedAxiosGet = memo(axios.get);
这个memo
函数将充当键值缓存。如果您的函数( axios.get
)的参数(在您的情况下是您的 URL)相同,则不会执行该函数。相反,将返回先前的结果。所以你可以使用这个内存版本
memoizedAxiosGet
在您的 useEffect
以确保不会针对该特定请愿重复网络请求。Check this demo integrated in React!
关于reactjs - 如何在 axios 中使用备忘录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61572578/