簡體   English   中英

React不會在map函數中呈現

[英]React won't render within map function

我正在嘗試使用JS函數map()渲染包含一些對象的數組。 但是,當我返回文本時,沒有顯示任何內容:

console.log(this.props.project.projects); // (2) [{…}, {…}]
  this.props.project.projects.map((item, index) => {
    console.log(item.projectDescription); //"Testproject"
    return (
        <div key={index}>
         {item.projectDescription}
        </div>
      )
  })

我只是沒有得到它,為什么沒有顯示文本,因為console.log(item.projectDescription)顯示我想要顯示的內容。

更新:當我將其更改為:

return this.props.project.projects.map((item, index) => (
        <div key={index} style={{ color: '#fff' }}>
         {item.projektBeschreibung}
        </div>
      ))

我已經考慮過使用foreach-method但我認為它實際上應該使用map() - 函數。

在這里,您還可以看到我的Component的render方法。

class ProjectRow extends Component {

  renderProjects() {
    console.log(this.props.project);
    if (this.props.project.loading) {
    return (
      <div style={{color: '#fff'}}>
        Loading
      </div>
    )
    } else {
      console.log(this.props.project.projects);
      this.props.project.projects.map((item, index) => {
        console.log(item);
        console.log(item.projektBeschreibung);
        console.log(index);
        return (
            <div key={index}>
             {item.projektBeschreibung}
            </div>
          )
      })
    }
  }

  render() {
    return (
      <div>
        {this.renderProjects()}
      </div>
    );
  }
}

當它碰到你的其他情況時, renderProjects函數不會返回任何內容。 這是一個使用示例:

renderProjects() {
  console.log(this.props.project);

  if (this.props.project.loading) {
    return (
      <div style={{color: '#fff'}}>
        Loading
      </div>
    )
  } else {
    console.log(this.props.project.projects);

    // added return statement here
    return this.props.project.projects.map((item, index) => {
      console.log(item);
      console.log(item.projektBeschreibung);
      console.log(index);
      return (
        <div key={index}>
          {item.projektBeschreibung}
        </div>
      )
    })
  }
}

為什么不使用下面的地圖?

render(){
  return(
    <div>
     {this.props.project.projects.map((item, index) => (
        <div key={index}>         
             {item.projectDescription}
        </div>
      ))}
  </div>
 )
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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