[英]How to better setup fetch with useEffect?
Im learning JS and React and I came to the code example below and some parts I don't understand properly.我正在学习 JS 和 React,我来到下面的代码示例和一些我不理解的部分。 The second.then is inside useUffect is this ok, or it's better to be in getData func?
second.then 在 useUffect 里面这样可以吗,还是在 getData func 里面更好? Also in render there is data**?**.map and I don't understand why we need?, is this ternary operator?
渲染中还有数据**?**.map,我不明白我们为什么需要?,这是三元运算符吗? Is so I thought that ternary operator requires: as a second parameter.
所以我认为三元运算符需要:作为第二个参数。 Thanks in advance!
提前致谢!
import React, { useState, useEffect } from "react";
const FetchData = () => {
const [data, setData] = useState(null);
const fetchURL = "https://jsonplaceholder.typicode.com";
const getData = () => fetch(`${fetchURL}/posts`)
.then((res) => res.json());
useEffect(() => {
getData().then((data) => setData(data));
}, []);
return (<div>
{data?.map(item => (
<ul>
<li>{item.title}</li>
</ul>
))}
</div>);
};
export default FetchData;
I think, your code is fine, Move getData and fetchURL
into useEffect
incase if there's any error.我认为,您的代码很好,如果有任何错误,请将
getData and fetchURL
移动到useEffect
中。
Also, You can simply use async/await
approach for the same.此外,您可以简单地使用
async/await
方法。
import React, { useState, useEffect } from "react";
const FetchData = () => {
const [data, setData] = useState(null) // here you can define `[]` if you don't want to check `?`
useEffect(() => {
const fetchURL = "https://jsonplaceholder.typicode.com";
const getData = async () => {
const res = await fetch(`${fetchURL}/posts`)
const result = await res.json();
setData(result);
}
getData()
}, []);
return (<div>
{data?.map(item => (
<ul>
<li>{item.title}</li>
</ul>
))}
</div>);
};
export default FetchData;
?
is Called Optional Chain Operator , which will help you to check whether the value is nullish (null or undefined)
.称为可选链运算符,它将帮助您检查值是否为空值
(null or undefined)
。
Basically, it just doing if (data) { data.map...}
基本上,它只是在做
if (data) { data.map...}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.