2017-12-20 9 views
0

私はJSON APIをフェッチし、配列にその結果をプッシュしたい:PushJsonの結果がReactJSに配列される正しい方法は何ですか?

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] is undefined

このエラー?

+1

誤差が小さいため、比較ミス、 'I <= j.results.lengthであり;'私はj.results.lengthを< 'でなければなりません;'しかし、あなた構造化は、私が編集した –

+0

@ShubhamKhatri正しくありません。しかし、私は結果が何もないので、反復でjsonを繰り返すための正しい方法は何ですか? – Mohammad

答えて

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') 
); 
関連する問題