![](/img/trans.png)
[英]How do I convert componentDidMount() and componentWillUnmount to the useEffect()?
[英]how do I convert my componentDidMount function to async componentDidMount type
这是我的 newsapp,这是我的组件文件夹的 News.js 文件
import React, { Component } from 'react'
import NeswItem from './NewsItem'
export class News extends Component {
constructor(){
super();
this.state={
data : null,
loading : false
}
}
componentDidMount(){
let url = //your news api url
fetch(url).then((res)=>{
res.json().then((result)=>{
console.log(result.articles)
this.setState({data:result.articles})
})
})
}
render() {
return (
<>
<div className="container my-3">
<h2>Top Headlines</h2>
<div className='row'>
{this.state.data ?
this.state.data.map((element)=>
<div className="col-md-4" key={element.url} >
<NeswItem title={element.title?.slice(0, 45)} description={element.description?.slice(0, 88)} imgurl={element.urlToImage} newsUrl={element.url}/>
</div>
)
: null
}
</div>
</div>
</>
)
}
}
export default News
我正在创建一个反应应用程序来显示最新消息,这是我的 App.js 文件
import './App.css';
import React, { Component } from 'react'
import Navbar from './components/Navbar';
import News from './components/News';
export default class App extends Component {
render() {
return (
<>
<News/>
</>
)
}
}
这是我的组件文件夹中的 NewsItem.js 文件
import React, { Component } from 'react'
export class NeswItem extends Component {
render() {
let {title, description, imgurl,newsUrl}= this.props;
return (
<div>
<div className="card my-3" style={{width: "18rem"}}>
<img src={!imgurl?"https://img.etimg.com/thumb/msid-96022092,width-1070,height-580,imgsize-60058,overlay-economictimes/photo.jpg":imgurl} className="card-img-top" alt="..."/>
<div className="card-body">
<h5 className="card-title">{title}...</h5>
<p className="card-text">{description}... </p>
<a href={newsUrl} target="_blanck" className="btn btn-primary">Read more</a>
</div>
</div>
</div>
)
}
}
export default NeswItem
我想将我的 componentDidMount function 转换为异步 componentDidMount 一个,但我无法做到。 注意:我正在使用来自 newsapi.org 的 api
只需在 componentDidMount 之前使用 async 关键字
async componentDidMount(){
let url = //your news api url
let res = await fetch(url)
let data = await res.json()
//rest of your code
}
你不能异步运行 componentDidMount,如果你想在接收数据之前显示加载,你现在所做的是可以的,你可以使用你已经定义的加载 state
这是示例:
componentDidMount(){
this.setState({loading:true})
let url = //your news api url
fetch(url).then((res)=>{
res.json().then((result)=>{
console.log(result.articles)
this.setState({data:result.articles,loading:false})
})
})
在 jsx 中:
<div>
{
this.state.loading ? 'loading...' : null
}
</div>
我想将我的 componentDidMount function 转换为异步 componentDidMount 一个
如果你那样做,就会产生误导。 React 调用componentDidMount
并完全忽略它提供的任何返回值。 因此,如果您将其设置为async
,它将返回一个 promise ,它不会被任何东西使用。
相反,要么做你正在做的事情(但处理错误),要么写一个async
function 来做它并调用它 function(同时处理错误)。
第一个选项:
componentDidMount() {
let url = "your news api url";
fetch(url)
.then((res) => {
if (!res.ok) {
throw new Error(`HTTP error ${res.status}`);
}
return res.json();
})
.then(({articles}) => {
console.log(articles);
this.setState({ data: articles });
})
.catch((error) => {
// ...handle/report error...
});
}
第二:
async #getArticles() {
let url = "your news api url";
const res = await fetch(url);
if (!res.ok) {
throw new Error(`HTTP error ${res.status}`);
}
const { articles } = await res.json();
console.log(articles);
this.setState({ data: articles });
}
componentDidMount() {
this.#getArticles().catch((error) => {
// ...handle/report error...
});
}
(我还添加了res.ok
的检查,因为你的代码在 我在这里描述的fetch
API 中成为 footgun 的猎物fetch
只拒绝它的 promise网络错误,而不是 HTTP 错误,如 404 或 500。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.