每次状态更改/呈现时都会触发数据获取自定义挂钩

时间:2020-06-15 10:06:49

标签: javascript reactjs react-native react-hooks

我有一个如下的自定义钩子

export const useFetchLesson = (lesson_id) => {
  const [response, setResponse] = useState(null);
  const [error, setError] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const languages = useSelector(state => getDeviceLanguage(state));

  useEffect(() => {
    const fetchData = async () => {
      setIsLoading(true);
      try {
        const requestUrl =  "https://school.com/" + lesson_id;
        const res = await fetch(requestUrl, {
          headers: header
        });
        const json = await res.json();
        setResponse(json);
        setIsLoading(false)
      } catch (error) {
        setError(error);
      }
    };

    fetchData();
  }, [lesson_id]);

  return { response, error, isLoading };
};

然后,我在组件之一中使用此自定义钩子,如下所示:

const TrueOrFalse = (props) => {
  const [lesson, setLesson] = useState();
  const [answer, setAnswer] = useState(null);

  let lesson_id = props.route.params ? props.route.params.id : 123;
  const res = useFetchLesson(lesson_id);

  useEffect(() => {
    if (res && res.response !== null)  {
      setLesson(res.response.data);
    }
  }, [res]);

  // then user's actions are set by calling setAnswer() such as
  // eg. <TouchableOpacity onPress={() => setAnswer(0)}>

我意识到每次调用setAnswer都会触发useFetchLesson。由于lesson_id在依赖项列表中,因此未调用API。

如何确保useFetchLesson仅被调用一次,而不是在每个渲染中都被调用?

0 个答案:

没有答案