2017-08-08 176 views
2

它的5個小時,我不明白是什麼問題 有人誰幫助我, 我只需要提取數據無法讀取屬性對象reactJS

import React,{Component} from 'react'; 
import axios from 'axios'; 
import CoinsConvert from '../data/data' 
import '../style/bootstrap.min.css'; 


class BoxInfo extends Component{ 

    constructor(){ 
    super(); 
    this.state={ 
     dataC:{} 
    } 

    } 
    componentWillMount(){ 
     let code=CoinsConvert[this.props.match.params.coin_url]; 
     axios.get(`https://www.cryptocompare.com/api/data/coinsnapshotfullbyid/?id=${code}`) 
     .then(da=>this.setState({dataC:da.data})).catch(()=>{console.error()}) 
    } 
render(){ 
    let dataC=this.state.dataC; 
    return(
     <div className="container"> 
     <div className="panel panel-default text-center" > 
     <div className="panel-heading" >{ dataC.Data.General.H1Text}</div> 
     <div className="panel-body "><img className="img-rounded" width="500" height="500" src={""} /></div> 
     </div> 
     </div> 
    ); 
    } 
} 

click to see image

例如JSON:cryptocompare

+0

'dataC.General.H1Text'代替'dataC.Data.General.H1Text' –

+0

你是什麼當你執行'console.log(this.state.dataC)'來獲得結構。 – abdul

回答

1

簡單的一個,api調用是異步的,所以this.state.dataC將會是{},直到你得到api響應。

在第一渲染當您嘗試訪問:

this.state.dataC.Data這將是不確定,當您嘗試訪問的undefined任何值,它將引發錯誤:

Can't read property XYZ of undefined.

解決方案:

把檢查數據,一旦你得到的數據,然後只渲染然後用戶界面。

像這樣:

render(){ 

    let dataC=this.state.dataC; 
    if(!Object.keys(dataC)) return null; 

    return (
     .... 
    ) 
} 

你也可以把支票上的每一個值,就像這樣:

{ dataC.Data && dataC.Data.General && dataC.Data.General.H1Text} 

建議:

,而不是使內部API調用componentWillMount,寫在裏面componentDidMount。所有的

+0

謝謝大家! – Aymen

0

最有可能的問題是由於您設置dataC作爲異步數據讀取的結果。因此componentWillMount將完成,然後render將被調用,並注意! - 在這一點上,數據可能還沒有被提取 - 所以在渲染你的dataC時未定義。

0

首先,你應該只在componentDidMount方法DOCS
,我認爲可能會導致問題的另一件事情得到異步數據,這條線:

this.setState({dataC:da.data}) 

你居然已經訪問data財產。 在渲染處理方法,你應該這樣做:

dataC.General.H1Text 

取而代之的是:嘗試

dataC.Data.General.H1Text 
相關問題