这是我的,我正在尝试获取 api 并在我的下一个反应组件中显示结果,但如果我可以在 componetmount 函数中设置状态,它可能会导致错误。 !this.state.articles.map 不是函数!请解决这个问题,并指出错误的原因,因为我是反应初学者。
import React, { Component } from "react";
import Newscompo from "./Newscompo";
class App extends Component {
constructor(props) {
super(props);
console.log('this is constructor');
// Set initial state
this.state = { articles: '' };
// // Binding this keyword
this.componentDidMount = this.componentDidMount.bind(this);
}
async componentDidMount() {
// Changing state
console.log('fetch the api now');
let url =
"https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=9c1cd38&pageSize=1";
let data = await fetch(url);
let parseData = await data.json();
console.log('The api is');
// console.log(parseData)
this.setState({ articles: parseData.articles });
}
render() {
return (
\<div\>
\<div className="container my-5"\>
\<div className="row "\>
<h2>Pratice-Headlines</h2>
{this.state.articles.map((obj)=\>{
return \
\
\
})}
</div>
</div>
</div>
);
}
}
export default App;
IN the Console the error is....
Uncaught TypeError: this.state.articles.map is not a function
render Practicstate.js:82
React 12
workLoop scheduler.development.js:266
flushWork scheduler.development.js:239
performWorkUntilDeadline scheduler.development.js:533
js scheduler.development.js:571
js scheduler.development.js:633
factory react refresh:6
Webpack 24
Practicstate.js:82
Please anyone solve this error and also mention that what mistake is taken by me!
您最初将文章声明为字符串。 React 按以下顺序调用生命周期方法:
constructor()
getDerivedStateFromProps()
render()
componentDidMount()
在你的例子中,在 render 方法中,map 函数抛出一个错误,因为你将 articles 声明为一个字符串。要解决此问题,请将文章声明为空数组。
constructor(props) {
super(props);
console.log('this is constructor');
// Set initial state
this.state = { articles: [] };
// // Binding this keyword
this.componentDidMount = this.componentDidMount.bind(this);
}