简体   繁体   中英

React items.map is not a function when items is an array?

Loading in an API and I'm getting .map isn't a function. Been looking through every example and followed them exactly but still getting this error. The error is of course happening at the .map in the ul tag

class Login extends Component {
  constructor(props) {
    super(props);
    this.state = {
      items: [],
      isLoaded: false
    };
  }

  componentDidMount() {
    fetch(
      "https://opentdb.com/api.php?amount=10&category=18&difficulty=easy&type=boolean"
    )
      .then(res => res.json())
      .then(json => {
        this.setState({ isLoaded: true, items: json });
      });
  }

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

    if (!isLoaded) {
      return <div>Loading...</div>;
    } else {
      return (
        <div className="App">
          <ul>
            {items.map(item => (
              <li key={item.results.question}>{item.results.question}</li>
            ))}
          </ul>
        </div>
      );
    }
  }
}

export default Login;

Your actual data is coming in json.results , so you need to set json.results in state like,

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

You need to iterate array like,

{ items.map(item => (
     <li key={item.question}>{item.question}</li>
))}

Demo

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