Let’s say we have a simple app look like this:

import { useEffect, useState } from "react";

function useFetch(config) {
  console.log("useFetch call");
  const [data, setData] = useState(null);
  useEffect(() => {
    if (config.url) {
      fetch(config.url)
        .then((response) => response.json())
        .then((json) => {
          setData(json);
        });
    }
  }, [config]);

  return { data };
}

export default function App() {
  const [url, setUrl] = useState(null);
  const { data } = useFetch({ url });
  return (
    <div className="App">
      <div>Hello</div>
      <div>{JSON.stringify(data)}</div>
      <div>
        <button onClick={() => setUrl("/jack.json")}>Jack</button>
        <button onClick={() => setUrl("/jelly.json")}>Sally</button>
      </div>
    </div>
  );
}

 

It has a useFetchcustome hook, when any button clicked, it will be invoked because urlchanges will trigger `useFetch` re-run.

  const [url, setUrl] = useState(null);
  const { data } = useFetch({ url });

 

But the problem here is that, it get stuck in infinity loop:

The reason is we passing {url}to useFetch, and inside useFetch, there is useEffect which deps on {url}.

 

Solution 1: instead passing object, just pass primitve value:

function useFetch(config) {
  console.log("useFetch call");
  const [data, setData] = useState(null);
  useEffect(() => {
    if (config.url) {
      fetch(config.url)
        .then((response) => response.json())
        .then((json) => {
          setData(json);
        });
    }
  }, [config.url]); // using config.url instead of config object
 
  return { data };
}

 

But what if we have also callback function inside config object?

export default function App() {
  const [url, setUrl] = useState(null);
  const onSuccess = () => console.log("success");
  const { data } = useFetch({ url, callback: onSuccess });
    
    
...

function useFetch(config) {
  console.log("useFetch call");
  const [data, setData] = useState(null);
  useEffect(() => {
    if (config.url) {
      fetch(config.url)
        .then((response) => response.json())
        .then((json) => {
          setData(json);
          config.callback();
        });
    }
  }, [config.url, config.callback]); // add callback as deps

  return { data };
}

Now again, it become crazy.

 

Solution to the callback problem, we can use useRefto resolve it:

function useFetch(config) {
  console.log("useFetch call");
  const [data, setData] = useState(null);
  const onSuccessRef = useRef(config.callback);
  useEffect(() => {
    if (config.url) {
      fetch(config.url)
        .then((response) => response.json())
        .then((json) => {
          setData(json);
          onSuccessRef.current?.();
        });
    }
  }, [config.url]);

  return { data };
}

This solution doesn’t work if callback changed… so we need to do

import { useEffect, useRef, useState, useLayoutEffect } from "react";

function useFetch(config) {
  const [data, setData] = useState(null);
  const onSuccessRef = useRef(config.callback);
  useLayoutEffect(() => {
    onSuccessRef.current = config.callback
  }, [config.callback])

  useEffect(() => {
    if (config.url) {
      fetch(config.url)
        .then((response) => response.json())
        .then((json) => {
          setData(json);
          onSuccessRef.current?.();
        });
    }
  }, [config.url]);

  return { data };
}

We use useLayoutEffectto keep ref callback up to date.

 

To improve, we can create a helper function:

import { useEffect, useRef, useState, useLayoutEffect } from "react";

function useCallbackRef(callback) {
  const callbackRef = useRef(callback);
  useLayoutEffect(() => {
    callbackRef.current = callback;
  }, [callback]);
  return callbackRef;
}

function useFetch(config) {
  const [data, setData] = useState(null);
  const savedOnSuccess = useCallbackRef(config.callback).current;
  useEffect(() => {
    if (config.url) {
      fetch(config.url)
        .then((response) => response.json())
        .then((json) => {
          setData(json);
          savedOnSuccess();
        });
    }
  }, [config.url]);

  return { data };
}

 

 

Add cancellation to the useEffect:

import { useEffect, useRef, useState, useLayoutEffect } from "react";

function useCallbackRef(callback) {
  const callbackRef = useRef(callback);
  useLayoutEffect(() => {
    callbackRef.current = callback;
  }, [callback]);
  return callbackRef;
}

function useFetch(config) {
  const [data, setData] = useState(null);
  const savedOnSuccess = useCallbackRef(config.callback).current;
  useEffect(() => {
    let isCancelled = false;
    if (config.url) {
      fetch(config.url)
        .then((response) => response.json())
        .then((json) => {
          if (!isCancelled) {
            setData(json);
            savedOnSuccess();
          }
        });
    }

    return () => {
      isCancelled = true;
    };
  }, [config.url]);

  return { data };
}

 

原文地址:http://www.cnblogs.com/Answer1215/p/16829497.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性