为什么自定义挂钩两次返回结果

问题描述 投票:0回答:2

下面的文章是关于创建一个用于获取数据的自定义钩子,这很简单。

https://dev.to/patrixr/react-writing-a-custom-api-hook-l16

尽管有一部分我不知道它是如何工作的。

为什么这个钩子返回两次结果? (isLoading = true isLoading = false)

function useAPI(method, ...params) {
    // ---- State
    const [data, setData]           = useState(null);
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError]         = useState(null);

    // ---- API
    const fetchData = async () => {
      onError(null);
      try {
        setIsLoading(true);
        setData(await APIService[method](...params));
      } catch (e) {
        setError(e);
      } finally {
        setIsLoading(false);
      }
    };

    useEffect(() => { fetchData() }, []);

    return [ data, isLoading, error, fetchData ];
}


function HomeScreen() {
  const [ users, isLoading, error, retry ] = useAPI('loadUsers');

  // --- Display error
  if (error) {
    return <ErrorPopup msg={error.message} retryCb={retry}></ErrorPopup>
  }

  // --- Template
  return (
    <View>
      <LoadingSpinner loading={isLoading}></LoadingSpinner>
      {
          (users && users.length > 0) &&
            <UserList users={users}></UserList>
      }
    </View>
  )
reactjs react-hooks
2个回答
2
投票

反应批次状态更新事件处理程序生命周期方法

fetchData不是其中的任何一个,因此将不进行批处理。

现在,当调用fetchData()时:

const fetchData = async () => {
  onError(null);
  try {
    // #1 async setState
    setIsLoading(true);

    const data = await APIService[method](...params);

    // #2 async setState
    setData(data);

  } catch (e) {
    setError(e);
  } finally {

    // #3 async setState
    setIsLoading(false);
  }
};

[成功后,有3个异步事件,我们只对#1#3感兴趣

  • 将加载状态从默认值true设置为false
  • false异步#1设置加载状态为setState

侧面注意:乍看之下,此挂钩有缺陷,在每个渲染上都重新分配了fetchData,您将得到缺少依赖项的警告。


0
投票

您的finally块在try块之后触发。

请注意,无论是否引发异常,都将执行finally块。

The finally block

© www.soinside.com 2019 - 2024. All rights reserved.