如何在axios中使用Memo?

pur*_*uru 4 reactjs react-hooks

在同一参数下从同一 API 返回响应后,如何避免重新访问 API

我如何将 useMemo 钩子与 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>
      );
  };
Run Code Online (Sandbox Code Playgroud)

Ras*_*mon 5

React.useMemo不保存以前结果的值。在 dev.to检查这个示例:

  const value = useMemo(() => expensiveFunction(a), [a]);
Run Code Online (Sandbox Code Playgroud)

a当它已经进行了存在的计算时,那么下次2就不再进行。2同样对于34

然而,它实际上只能记住一个值。如果第一次计算 ,1接下来又计算2,它就不会再记住结果是什么1。当再次提供时1 ,它会重新进行计算。

因此,在您的情况下,您应该创建一个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);
Run Code Online (Sandbox Code Playgroud)

这个memo函数就像一个键值缓存。如果函数 ( ) 的参数(在您的情况下为 URL)axios.get相同,则该函数将不会被执行。相反,将返回之前的结果。

memoizedAxiosGet因此,您可以在您的应用程序中使用这个记忆版本useEffect来确保该特定请求不会重复网络请求。

检查这个集成在 React 中的演示!