[英]I am getting read property map of undefined.I have tried everything but nothing worked
I have tried many solutions given on StackOverflow as well as on other platforms but nothing worked.我在 StackOverflow 以及其他平台上尝试了许多解决方案,但没有任何效果。 I am new to ReactJs and I am unable to understand what is wrong in this code that I am getting this error.
我是 ReactJs 的新手,我无法理解我收到此错误的代码有什么问题。
componentDidMount() {
console.log("component did mount");
axios.get('http://localhost:3000/')
.then(response => {
if (response.data.length > 0) {
this.setState({
blogs: response.data
});
}
})
.catch((error) => {
console.log(error);
})
}
render(){
console.log("inside render ");
var b=this.state.blogs.map((blog)=>{
console.log(blog);
var taggu=blog.tag.map((tag)=>{
return(
<span>{tag}</span>
)
});
var con=blog.content.slice(0,100);
return(
<Col className="my-1" lg="4" sm="6" >
<Card key={blog._id}>
<CardHeader tag="h3">{blog.topic}</CardHeader>
<CardBody>
<CardTitle tag="h5">By {blog.writer.username}</CardTitle>
<CardText>{con}... </CardText>
<Button>Learn More</Button>
</CardBody>
<CardFooter>{taggu}</CardFooter>
</Card>
</Col>
)
});
return ( <div className="App">{b}</div>)
} }
The Promise
from axios
does not resolve
instantly and it is very likely that the render
function was called before来自
Promise
的axios
不会立即resolve
,很可能之前调用了render
function
this.setState({
blogs: response.data
});
was executed, meaning that this.state.blogs
is undefined.已执行,这意味着
this.state.blogs
未定义。
You could either add您可以添加
this.setState({
blogs: []
});
in the constructor or check whether this.state.blogs
is undefined before calling its map function:在构造函数中或在调用其 map function 之前检查
this.state.blogs
是否未定义:
render(){
console.log("inside render ");
if(!this.state.blogs)
return <span>Loading...</span>;
// Rest of the code below...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.