2017-09-21 6 views
0

나는 반응을 사용하여 API에서 가져온 데이터를 렌더링합니다. 내 코드는 다음과 같습니다 : 나는 렌더링 함수 (this.state.lists를) CONSOLE.LOG정의되지 않은 오류 'username'속성을 읽을 수 없습니다.

var App = React.createClass({ 

getInitialState : function(){ 

    return { 
     lists: [] 
    } 
}, 

componentDidMount: function(){ 

    fetch('https://fcctop100.herokuapp.com/api/fccusers/top/recent') 
    .then(function(result){ 
     return result.json(); 
    }).then(function(jsonResult){ 
     this.setState({ 
      lists: jsonResult 
     }); 
    }.bind(this)); 
    }, 



render: function(){ 
    console.log(this.state.lists); 
    return(
     <div>{this.state.lists[0].username}</div> 

     ); 
    } 
}); 

ReactDOM.render(<App />, document.getElementById('container')); 

과 나는 API에서 전체 데이터를 얻었으나, 나는 데이터의 일부를 렌더링 할 때, 내가 가진 '속성을 읽을 수 없습니다'사용자 정의 '오류'의 오류. getInitialState 함수에서 [ '']를 설정하고 {this.state.lists [0] .username}을 렌더링하면 작동하지만 인덱스를 1로 변경하면 같은 오류가 발생합니다. 나는 라이프 사이클 기능과 관련이 있다고 생각한다. 그러나 나는 그것을 알아낼 수 없다. API에서 가져온 데이터는 다음과 같습니다. enter image description here

저는이 작업을 3 시간 동안했습니다. 누군가 나를 도울 수 있기를 바랍니다. 매우 감사!

답변

0

오류가 비어 있습니다. componentDidMount() 초기 렌더링 후 라이프 사이클 메서드가 호출됩니다.

render: function(){ 
    console.log(this.state.lists); 
    return(
     <div>{this.state.lists.length >0 ?this.state.lists[0].username:null}</div> 

     ); 
    } 
}); 
+0

정말 고마워요! 나는 일할 수있어! 그것은 매우 도움이되었습니다. 컴포넌트 라이프 사이클을 훨씬 더 잘 이해해야합니다! 고마워요! –

+0

@BoHuang 환영합니다. 더 나은 이해를 위해 https://facebook.github.io/react/docs/react-component.html을 읽어 보시기 바랍니다. – Ved

1

this.state.lists이 처음으로 정의되지 않기 때문에 이러한 현상이 발생합니다. 코드 아래 사용이 처음

render() 방법 GET의가 componentDidMount() 전에 호출하고 this.state.lists 그 시간에 [] 때문에 일어나는에 대한 우회 얻을, 따라서 this.state.list[0]의 도움으로 설정 갈 것 undefined 될 것입니다 다음 this.state.lists까지 this.setState() 때문에 this.state.lists를 렌더링하는 모든 데이터가 없습니다 초기에 대한

return(
    { this.state.lists.length && <div>this.state.lists[0].username </div> } 
); 
+1

'this.state.lists'는 정의되지 않았습니다. 그것은 비어 있습니다. – Ved

+0

그가 생성자()에 이미 설정 한대로 내 비우면 비어 있습니다. – squiroid

+0

고마워요! 코드를 복사하고 붙여 넣었습니다. 내가 오타 받았다 –

0

문제는 렌더링 전에 데이터를 가져 오지 않았기 때문입니다.

componentDidMount(){ 
     fetch('https://fcctop100.herokuapp.com/api/fccusers/top/recent') 
      .then(function(result){ 
      return result.json(); 
     }).then(function(jsonResult){ 
      this.setState({ 
       lists: jsonResult 
      }); 
     }.bind(this)); 
    } 

componentWillReceiveProps(nextProps) { 
    this.renderView(); 
} 

renderView =() => { 
if (this.state.lists){ 
     return <div>{this.state.lists[0].username}</div> 
} else { return <div><p>loading</p></div> 
} 
render() { 
    return (
    {this.renderView()} 
) 
ReactDOM.render(<App />, document.getElementById('container')); 
+0

이렇게 연습이 너무 깔끔합니다! –

관련 문제