简体   繁体   中英

What's the right way for push json result to array in ReactJS?

I want fetch a json api and push that result into an array:

 import React from 'react'; import ReactDOM from 'react-dom'; function Users(){ const url = 'https://randomuser.me/api/?results=5'; let nodes = []; fetch(url) .then(response => { return response.json(); }) .then(j => { for( var i = 0; i <= j.results.length; i++ ){ nodes.push(<li>{j.results[i].name.first}</li>); } }); return( <ul>{nodes}</ul> ); } ReactDOM.render( <Users />, document.getElementById('main') ); 

But I have the following error in the console:

TypeError: j.results[i] is undefined

How can I fixed this error?

I'm not sure that this is react way of fixing this problem. Here is the solution of your problem:

class Hello extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      nodes: []
    }
  }

  componentDidMount(){
    this.fetchData();
  }

  fetchData(){
    console.log('here')
    const url = 'https://randomuser.me/api/?results=5';
    fetch(url)
      .then(response => response.json())
      .then(data => {
        const nodes = data.results;
        this.setState({nodes})
      })
  }

  render(){
    return (
      <ul>
        {this.state.nodes.map(node => <li key={node.name.first} >{node.name.first}</li>)}
      </ul>
    )
  }
}

Worked example here . Hope it makes sense.

import React from 'react';
import ReactDOM from 'react-dom';

class Users extends React.Component{
  constructor(props) {
     super(props)
     this.state = {
       nodes: []
     }
     this.load()
  }

  load() {
    const url = 'https://randomuser.me/api/?results=5';
    return fetch(url)
    .then(response => response.json())
    .then(({results:nodes}) => this.setState({nodes}))
   }

   render() {
     let {nodes} = this.state
     return <ul>{nodes.map(({name:{first}}) => <li>{first}</li>)}</ul>
   }
 }

 ReactDOM.render(
     <Users />,
     document.getElementById('main')
 );

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