在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問(wèn)答/HTML/ 子組件無(wú)法同步讀取父組件請(qǐng)求的異步數(shù)據(jù) / Cannot read prope

子組件無(wú)法同步讀取父組件請(qǐng)求的異步數(shù)據(jù) / Cannot read property of undefined

當(dāng)父組件異步獲取數(shù)據(jù)傳遞給子組件,但是子組件調(diào)用數(shù)據(jù)的時(shí)候發(fā)現(xiàn)異步數(shù)據(jù)還沒(méi)有返回結(jié)果,報(bào)出 undefined 錯(cuò)誤, 請(qǐng)問(wèn)有什么解決方式嗎

分析原因應(yīng)該是子組件訪問(wèn) props 數(shù)據(jù)時(shí), 父組件的異步數(shù)據(jù)還沒(méi)有返回, 不知道是不是?

大致代碼如下。

class ParentComponent extends React.Component {
    constructor () {
        // initial
    }
    
    componentDidMount () {
        fetch('url').then(data => {
            this.setState({
                data: data,
            );
        })
    }
    
    render () {
        renturn(
         <ChildComponent data={this.state.data} />
        );
    }
        
}

class ChildComponent extends React.Component {
    constructor () {
        // initial
    }
    
    render () {
        let { dataItem } = this.props.data; // Err: Cannot read property of undefined
        console.log(this.props.data); // log empty arr first, then log full data / 先打印出了空數(shù)組, 然后打印出了正確數(shù)據(jù)
    }
}

感謝。

回答
編輯回答
脾氣硬

通過(guò)Promise來(lái)處理。

2018年6月28日 17:35