简体   繁体   中英

ReactJS TypeError: undefined is not a function (near '...this.state.data.map...')

I am new at React and trying to learn it. I am getting data from API and I will use the data. It returns money rates based on 'USD'. I am gonna use that data for convert money but I am getting this error: Error here

截屏

I don't know what the problem is.

import React, { Component } from 'react';
import './App.css';


class App extends Component {

    constructor (props) {
        super(props)
        this.state = {data: 'false'};
    }

    componentDidMount(){
        this.getData();
    }

    getData = () => {
        fetch("https://openexchangerates.org/api/latest.json?app_id=88a3d2b24b174bf5bec485533a3bca88")
            .then(response => {
                if (response.ok) {
                    return response;
                } else {
                    let errorMessage =
                        '${response.status(${response.statusText})',
                  error = new Error(errorMessage);
                  throw(error);
                 }
                })
                .then(response => response.json())
                .then(json =>{
                   console.log(json);
                   this.setState({ data: json.data })
                });
     
    }

  render() {



    return (
      <div className="App">
        <header className="App-header">
          <h1 className="App-title">React App</h1>
        </header>

          {
              this.state.data &&
              this.state.data.map( (item, key) =>
                  <div key={key}>
                      {item}
                  </div>
              )}

      </div>
    );
  }
}

export default App;

Thanks for your time.

Set your initial data property in the state to an empty array [] . A stringified 'false' evaluates to true which is why it tries to call the map function, but string doesn't have a map function.

 constructor (props) {
        super(props)
        this.state = {data: []};
    }

Working example here

Because this.state.data is not an array , it's a string .

Just use the below code and remove this.state.data && from render method.

constructor (props) {
    super(props)
    this.state = {
        data: []
    };
}

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