React useEffect hook 和 Async/await 自己的获取数据功能? [英] React useEffect hook and Async/await own fetch data func?
问题描述
我尝试创建一个从服务器获取数据的函数,它工作正常.但我不确定这是否正确?
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>;
};
这篇关于React useEffect hook 和 Async/await 自己的获取数据功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!