[英]How to turn vanilla js fetch code into react?
I wrote this code in Vanilla JS我在 Vanilla JS 中编写了这段代码
function MovieGrid() {
fetch(apiUrl)
.then(function(res){
return res.json();
})
.then(function(data) {
console.log(data);
return( `<ul>
<li><img src="https://image.tmdb.org/t/p/w185/${data.results.poster_path}" alt="" /></li>
<li>${data.results.title}</li>
</ul>`)
})
.catch(function(err){
console.log(err);
});}
This code works in vanilla but the app I'm working on is developed in react.这段代码适用于 vanilla,但我正在开发的应用程序是在 react 中开发的。 So how do I turn this code above to working react component?
那么如何将上面的代码转换为可工作的 React 组件呢?
Always make network request after the component mounted组件安装后总是发出网络请求
Use fetch API inside useEffect()
if you are using functional component如果您使用功能组件,请在
useEffect()
使用 fetch API
example:例子:
import {
useEffect
} from 'react';
const Component = () => {
useEffect(() => {
// use fetch inside here
}, [])
return (
// .... JSX Element
)
}
export default Component;
Use fetch API inside componentDidMount()
if you are using class component;如果您使用的是类组件,请在
componentDidMount()
使用 fetch API;
More helpful article in this link fetch data in react此链接中更有用的文章在反应中获取数据
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.