Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
364 views
in Technique[技术] by (71.8m points)

javascript - I keep getting this TypeError: Cannot read property 'map' of undefined

I am trying to render this data from the API onto my page. I am aware that what I am trying to render isn't in the typical array its a javascript object which is throwing me off. With my code, as is, the API data is there its just a matter of being able to access because .map isn't working because the data I have is not an array. Do I need to create another function?

I am not sure

import React from 'react';
import './App.css';

class App extends React.Component {
 
  state = {
  apiData: []
  }
 
  render() {   
    
  console.log('api datat is')

    return (
      <div>
        <center>
        <h1>hello something</h1></center>
        {this.state.apiData.map(title => title.rendered)}
      </div>
    )
  }
 
  componentDidMount() {
    fetch('http://www.mocky.io/v2/5dece3d333000052002b9037')
      .then(response => response.json())
      .then(data => {
        this.setState({
          apiData: data.data
        })
      })        
      console.log("component fetched data")
  }
}
 
export default App

Any help would be great.

I am still learning how to code so be nice

question from:https://stackoverflow.com/questions/66066154/i-keep-getting-this-typeerror-cannot-read-property-map-of-undefined

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Look at the API response:

{
  "id": 233383,
  "date": "2019-10-28T10:50:53",
  "date_gmt": "2019-10-28T10:50:53",
  "modified": "2019-10-28T10:55:14",
  "modified_gmt": "2019-10-28T10:55:14",
  "link": "https://www.stylist.co.uk/long-reads/friendship-friends-whatsapp-facebook-messenger-social-media-group-chat-best-friends-psychology-advice/233383",
  "title": {
    "rendered": "Whatsapp and Facebook Messenger: how group chat is changing the dynamic of our friendships"
  },
  "slug": "whatsapp-and-facebook-messenger-how-group-chat-is-changing-the-dynamic-of-our-friendships",

etc.

It does not have a .data property, so

  .then(data => {
    this.setState({
      apiData: data.data
    })
  }) 

sets undefined to this.state.apiData.

The only rendered exists in the one top-level object in the response, so you should remove the .map entirely, something like:

  .then(data => {
    this.setState({
      apiData: data
    })
  })  
<h1>hello something</h1></center>
{this.state.apiData.title.rendered}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...