【问题标题】:unable to display the data in react but able to see in the console无法在反应中显示数据但能够在控制台中看到
【发布时间】:2021-05-22 01:58:00
【问题描述】:

*****我的代码 *****

export default class App extends Component {


  

  state = {
    arraydata: []   };


  componentDidMount = () => {
    this.getmongodbdata();   }

  getmongodbdata = () => {
    axios.get('http://localhost:8080/fetch').then(res => {
      console.log(res.data,)
      console.log('Data is recieved')
      this.setState({arraydata: res.data})
      
    })
      .catch(() => {
        alert('Sorry, could not able to fetch the data');
      })   }
  


     render() {
    return (
      <div className="Main">
       <header className="App-header">
          
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to Future</h1>
       </header> 


       <h1> hello world</h1>

        <ul key={'qw'}>
          {this.state.arraydata.map((data) => {
            <li key={'ui'}>
              {data._id}
            </li>
            console.log(data._id)
          })}
        </ul>

        


      <div className={"blog-"}>
      
      
      
      </div>
      </div>
    )   } }

*我在控制台的输出和反应

只是试图显示此数据但无法显示。

【问题讨论】:

    标签: javascript node.js reactjs jsx reactstrap


    【解决方案1】:

    map 应该返回要打印的数组。试试这个

    <ul key={'qw'}>
      {this.state.arraydata.map((data, index) => {
        return <li key={`ui-${index}`}>
          {data._id}
        </li>
      })}
    </ul>
    

    如何在其中显示其他数据,例如获取警报数组 在里面输入

    从帖子中我看到site.alerts 是一个数组。您需要使用相同的方法使用map 进行打印。

    例子

    <ul key={'qw'}>
      {this.state.arraydata.map((data, index) => {
        return <li key={`ui-${index}`}>
          {data._id}
          <ul key={`alert-ui-${index}`}>
             {data.site.alerts.map((alertData, alertIndex)=>{
               return <li key={`alert-li-${alertIndex}`}>{alertData.alert}</li> 
             });
          </ul>
        </li>
      })}
    </ul>
    

    【讨论】:

    • 我怎样才能在其中显示其他数据,比如在其中输入警报数组:
        {this.state.arraydata.map((data , index) => { return
      • ui-${index}}> {data.site.alerts}
      • })}
    • 首先感谢您给我时间,我尝试更新答案,但得到了错误(地图无法读取未定义的属性)
    • 试试data.site[index].alerts.map。如果 site 数组中有多个元素,则需要迭代每个站点
    • 抱歉回复晚了,我试过了,现在可以了。非常感谢您在这方面为我提供的帮助。谢谢?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-23
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    • 1970-01-01
    • 2022-12-11
    相关资源
    最近更新 更多