简体   繁体   中英

TypeError: Cannot read property 'map' of undefined. What should I fix?

I got the error when I tried to get some datas from api.

Then I searched how to solve this error but I couldn't solve. I want to solove this error. I don't know Why do I get this error. What should I fix my code?? Please tell me any ideas. thank you for reading !

this is my error.

TypeError: Cannot read property 'map' of undefined

and message image. 在此处输入图像描述

this is my code.

import React,{ Component } from 'react';

class Exchange extends Component {
  constructor(props){
    super(props);
    this.state = {
      isLoaded: false,
      items: [],
    }
  }
  componentDidMount(){
    fetch('https://api.exchangeratesapi.io/latest')
    .then(res => res.json())
    .then(json => {
      this.setState({
        isLoaded: true,
        items: json.items,
      })
    })
    }

    render(){
      var { items,isLoaded } = this.state;

      if(!isLoaded){
        return <div>...Loading</div>;
      }else{
        return (
          <div>
            <ul>
              {items.map(item =>(
                <li key={item.rates}>{item.CAD}</li>
              ))}
            </ul>
          </div>
        )
      }
    }
}

 export default Exchange;

and this is using api. 在此处输入图像描述

I think the way you access the data from api is wrong it should be

this.setState({
    isLoaded: true,
    items: json.rates //json.rates not json.items
});

and when rendering it, map expecting a array so you have do something like this

<ul>
    {Object.keys(items).map(key => (
        <li key={key}>{key} - {items[key]}</li>
     ))}
</ul>

Demo

There is no attribute items in the json response. That's why items is undefined after following statement: items: json.items .

Also, map() is only applicable to array. Response from the API you are calling is not Array.

You can modify code something like

this.setState({
    isLoaded: true,
    items: json,
})

And

<ul>              
    <li>{items.rates.CAD}</li>
</ul>

To change the state of the array this.setState({ items: [...this.state.items, itemsArr] }) If the your response of API is array you can follow the above way.

But in your API response it seems like object, to push object into an array gothrough the link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM