簡體   English   中英

我正在讀取未定義的屬性 map。我已經嘗試了一切但沒有任何效果

[英]I am getting read property map of undefined.I have tried everything but nothing worked

我在 StackOverflow 以及其他平台上嘗試了許多解決方案,但沒有任何效果。 我是 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>)

}

來自Promiseaxios不會立即resolve ,很可能之前調用了render function

this.setState({ 
  blogs: response.data
});

已執行,這意味着this.state.blogs未定義。

您可以添加

this.setState({ 
  blogs: []
});

在構造函數中或在調用其 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM