2017-12-20 1 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

오류 때문에 작은 비교 실수이며, '내가 <= j.results.length,'해야'내가 j.results.length을 <;'하지만 @ShubhamKhatri 내가 편집 –

+0

당신 구조가 올바르지 않습니다, 하지만 결과가 없으므로 반복되는 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') 
); 
관련 문제