2017-09-21 28 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.setState()this.state.listsそれまでは、最初のレンダリングのために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

この練習はきちんとしています! –

関連する問題