本文介绍了使用React Hooks多次获取数据axios的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从Github用户和他的仓库中获取全局信息(并获得固定的仓库将是很棒的).我尝试通过异步等待来做到这一点,但这是正确的吗?我有4次reRender(4次控制台日志).提取所有数据后是否可以等待所有组件重新渲染?

I would like to get global information from Github user and his repos(and get pinned repos will be awesome). I try to make it with async await but It's is correct? I've got 4 times reRender (4 times console log). It is possible to wait all component to reRender when all data is fetched?

function App() {
  const [data, setData] = useState(null);
  const [repos, setRepos] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      const respGlobal = await axios(`https://api.github.com/users/${username}`);
      const respRepos = await axios(`https://api.github.com/users/${username}/repos`);

      setData(respGlobal.data);
      setRepos(respRepos.data);
    };

    fetchData()

  }, []);

  if (data) {
    console.log(data, repos);
  }

  return (<h1>Hello</h1>)
}

推荐答案

批处理多个状态更新,但仅在事件处理程序内部同步发生而不是setTimeoutsasync-await wrapped methods时才进行.

Multiple state updates are batched but but only if it occurs from within event handlers synchronously and not setTimeouts or async-await wrapped methods.

此行为类似于类,因为在您的情况下,由于发生了两个状态更新调用,因此它执行两个状态更新周期

This behavior is similar to classes and since in your case its performing two state update cycles due to two state update calls happening

因此,最初您有一个初始渲染,然后有两个状态更新,这就是组件渲染三次的原因.

So Initially you have an initial render and then you have two state updates which is why component renders three times.

由于案例中的两个状态是相关的,因此您可以创建一个对象并一起更新它们

Since the two states in your case are related, you can create an object and update them together liek

function App() {
  const [resp, setGitData] = useState({ data: null, repos: null });

  useEffect(() => {
    const fetchData = async () => {
      const respGlobal = await axios(
        `https://api.github.com/users/${username}`
      );
      const respRepos = await axios(
        `https://api.github.com/users/${username}/repos`
      );

      setGitData({ data: respGlobal.data, repos: respGlobal.data });
    };

    fetchData();
  }, []);

  console.log('render');
  if (resp.data) {
    console.log("d", resp.data, resp.repos);
  }

  return <h1>Hello</h1>;
}

工作演示

Working demo

这篇关于使用React Hooks多次获取数据axios的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 13:54