reactjs - 如何在 axios 中使用备忘录?

标签 reactjs react-hooks

在同一参数下从同一 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 being 2, then it won't do it for 2 next time. Likewise for the 3 or 4.

However, it really can only memoize one value. If the first time, it did the calculation for 1, and next it did the calculation for 2, it won't remember what the result is for 1 any more. When supplied with 1 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/

相关文章:

reactjs - react useReducer 和上下文 : how to provide state selectors?

javascript - React - 如何通过将 State 作为 props 传递来根据另一个下拉列表中的选择来填充一个下拉列表

reactjs - React Native 项目中哪些文件夹应该被 git 忽略?

reactjs - 在useEffect中,不提供依赖数组和提供空依赖数组有什么区别?

javascript - 如何为 map 函数中的每个迭代分配一个新的 ref?

javascript - ESLint 希望 setSate 作为 useEffect 的依赖项,但这会导致无限循环(react-hooks/exhaustive-deps)

javascript - 使用 React hooks 获取数据清理异步回调

reactjs - React 中的 node => {this.node = node } 是什么

android - 在发布版本上 react native AAPT错误

javascript - 使用带有 "async"的 useEffect 钩子(Hook)