2017-06-14 23 views
1

ネストされた配列の "レコード"をプルすることを目標としています。私の現在の出力は反応コンソール内の配列を表示しますが、エラーがあります。私は可能な限り簡潔にしようと努力しますが、物事を短く保ちます。オブジェクト内にネストされた配列をマップ内に返します。

エラー画面に_getRecordsを参照している3行がありますので、_getRecordsは問題の子です。

class RecordBox extends Component { 
    constructor() { 
    super(); 

    this.state = { 
    showComments: false, 
    results: [] 
    }; 
} 
render(){ 
    const records = this._getRecords(); 
    return (
     // jsx template code... 
    ); 
    } 
    // API Call 
_fetchRecords() { 
    $.ajax({ 
    method: 'GET', 
    url: 'http://apidata:8888/data.json', 
    success: (results) => { 
    this.setState({ results }); 
    }, 
    error:() => { 
    console.log('error'); 
    } 
    }); 
} 
_getRecords() { 
    // TypeError: this.state.results.map is not a function... 
    return this.state.results.map((record) => { 
     return <Comment body={record["Contractor Name"]} /> 
    }); 
    } 
} 

私は以下のようなフィードを持っています。私はこれを変更する許可がありません。

{ 
"result": { 
    "records": [ 
    { 
     "id": 1, 
     "email": "[email protected]", 
     "author": "Clu", 
     "Contractor Name": "Just say no to love!!", 
     "avatarUrl": "https://placeimg.com/200/240/any" 
    },{ 
     "id": 2, 
     "email": "[email protected]", 
     "author": "Anne Droid", 
     "Contractor Name": "I wanna know what love is...", 
     "avatarUrl": "https://placeimg.com/200/240/any" 
    } 
    ] 
} 
} 

REACT Console

私はES6に新しいですし、私と一緒に裸してくださいようにも反応します。

+2

なぜ、_getRecordsがクラスの外にありますか? – VivekN

+0

'this.state.results'には何を保存していますか? – BravoZulu

+0

@arkjosephどのように_getRecordsをどこから呼び出すのですか? – VivekN

答えて

0

_fetchRecords機能は、に変更する必要があります - 私はあなたがちょうどいい事に状態を設定していないと思います

_fetchRecords() { 
    $.ajax({ 
    method: 'GET', 
    url: 'http://apidata:8888/data.json', 
    success: (results) => { 
    this.setState({ results: results.result.records }); 
    }, 
    error:() => { 
    console.log('error'); 
    } 
    }); 
} 
1

。あなたの現在のオブジェクト:state.results現在はオブジェクトです。ちょうどあなたがあなたの状態を設定するとき、あなたはにresults.result.records

this.setState({ results: results.result.records }) 

state.resultsを設定し、あなたも行うことができます一つのことはJSXコードで直接結果をマッピングし、使用して飛ばしていることを確認してください_getRecords関数。

<div> 
    { 
    this.state.results.map((record) => { 
     return <Comment /> 
    } 
    } 
</div> 

これは私が読むのが簡単なので、通常これを書く方法ですが、個人的な好みです。

こちらがお役に立てば幸いです。

関連する問題