我正在阅读 属性 地图 undefined.I 已经尝试了所有方法但没有任何效果
I am getting read property map of undefined.I have tried everything but nothing worked
我已经尝试了 Whosebug 以及其他平台上提供的许多解决方案,但没有任何效果。我是 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>)
}
来自 axios
的 Promise
不会立即 resolve
并且很可能在
之前调用了 render
函数
this.setState({
blogs: response.data
});
被执行了,意味着this.state.blogs
未定义。
您可以添加
this.setState({
blogs: []
});
在构造函数中或在调用其映射函数之前检查this.state.blogs
是否未定义:
render(){
console.log("inside render ");
if(!this.state.blogs)
return <span>Loading...</span>;
// Rest of the code below...
我已经尝试了 Whosebug 以及其他平台上提供的许多解决方案,但没有任何效果。我是 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>)
}
来自 axios
的 Promise
不会立即 resolve
并且很可能在
render
函数
this.setState({
blogs: response.data
});
被执行了,意味着this.state.blogs
未定义。
您可以添加
this.setState({
blogs: []
});
在构造函数中或在调用其映射函数之前检查this.state.blogs
是否未定义:
render(){
console.log("inside render ");
if(!this.state.blogs)
return <span>Loading...</span>;
// Rest of the code below...