在JactJS中将json结果推送到数组的正确方法是什么?

问题描述 投票:0回答:2

我想获取一个json api并将该结果推送到一个数组中:

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')
);

但是我在控制台中有以下错误:

TypeError:j.results [i]未定义

我该如何修复此错误?

javascript reactjs ecmascript-6
2个回答
1
投票

我不确定这是解决这个问题的react方法。以下是您的问题的解决方案:

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>
    )
  }
}

工作示例here。希望它有意义。


0
投票
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')
 );
© www.soinside.com 2019 - 2024. All rights reserved.