反应useEffect钩子和Async/await自己的获取数据功能? [英] React useEffect hook and Async/await own fetch data func?

查看:99
本文介绍了反应useEffect钩子和Async/await自己的获取数据功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个用于从服务器获取数据的函数,并且该函数有效. 但是我不确定这是否正确吗?

I tried to create a function for fetching data from the server, and it works. But I am not sure if that the right way?

我使用 useState useEffect Async/Await 创建了一个用于提取数据的功能组件:

I created a function component to fetching data, using useState, useEffect and Async/Await :

import React, { useState, useEffect } from "react";

const Fetch = () => {
  const [data, setData] = useState(null);
  useEffect(() => {
    const fetchData = async () => {
      let res = await fetch(
        "https://api.coindesk.com/v1/bpi/currentprice.json" //example and simple data
      );
      let response = await res.json();
      setData(response.disclaimer); // parse json
      console.log(response);
    };
    fetchData();
  }, []);
  return <div>{data}</div>;
};

export default Fetch; // don't run code snippet, not working, this component must be imported in main

我不确定要在哪里 调用 fetchData 功能的地方.我在useEffect里面做吗?正确的位置?并且,此呼叫将仅发生一次?因为我使用 [] ?

Where I am not sure is a place where to call the fetchData function. I do that inside useEffect? Right place? And, this call will happen only one? Because i use []?

通常,您将如何做这样的事情?

Generally, how would you do something like this?

推荐答案

总体而言,您的工作方向正确.为了获取数据,您需要使用useEffect并将[]作为第二个参数传递,以确保仅在初始安装时触发.

Overall, you are heading in the right direction. For fetching data, you'd wanna use useEffect and pass [] as a second argument to make sure it fires only on initial mount.

我相信您可以从去耦fetchJson函数并使其更通用的方法中受益,例如:

I believe you could benefit from decoupling fetchJson function and making it more generic, as such:

const fetchJson = async (url) => {
  const response = await fetch(url);
  return response.json();
};

const Fetch = () => {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetchJson("https://api.coindesk.com/v1/bpi/currentprice.json")
      .then(({ disclaimer }) => setData(disclaimer));
  }, []);

  return <div>{data}</div>;
};

这篇关于反应useEffect钩子和Async/await自己的获取数据功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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