使用 React Hooks 多次获取数据 axios [英] Multiple fetch data axios with React Hooks

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

问题描述

我想从 Github 用户和他的存储库中获取全局信息(获得固定存储库会很棒).我尝试使用 async await 来实现,但这是正确的吗?我有 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包装方法.

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 like this:

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>;
}

工作演示

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆