[英]How to make api call and populate in render in react function based view
import React, { useState, useEffect} from 'react';
const App = () => {
const [setData] = useState('');
useEffect(() => {
fetch('https://jsonplaceholder.com/users/')
.then(res => res.hson())
.then(res => {
setData(res);
})
});
return ({
setData.map(data => {
<h1>{data.name}</h1>
})
});
}
Here I am making an api call in react using functional component. 在这里,我使用功能组件在响应中进行api调用。 It is coming the result.
结果来了。
But I am not able to populate result in render. 但是我无法在渲染中填充结果。 Showing map is not a function error.
显示地图不是功能错误。
Please have a look. 请看一看。
import React, { useState, useEffect} from 'react';
const App = () => {
const [data, setData] = useState([]);
useEffect(() => {
fetch(`https://jsonplaceholder.com/users/`)
.then(res => res.json())
.then(res => {
setData(res);
})
}, []);
return !!data && data.map(data => <h1>{data.name}</h1>);
}
First use an array as the default value for your state 首先使用数组作为状态的默认值
Use the data variable to loop over the results 使用数据变量遍历结果
The useState hook returns 2 values, the data and the function to change that data useState挂钩返回2个值,数据和更改该数据的函数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.