2017-06-14 15 views
1

目標是拉入嵌套數組「記錄」。我當前的輸出顯示反應控制檯內的數組,但出現錯誤。我會盡可能簡潔,但會保持簡短。對象內的反應貼圖嵌套陣列

錯誤屏幕有3行引用_getRecords,所以im positive是_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當前是一個對象。只要確保當你設置你的狀態,你設置state.resultsresults.result.records

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

有一件事你也可以做的是在JSX代碼的結果直接映射,並使用箕斗_getRecords函數。

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

這是我通常寫這個的方式,因爲它對我來說更容易閱讀,但它是個人偏好。

我希望這有助於!