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

鍍金池/ 問答/HTML/ react 組件相關(guān)問題

react 組件相關(guān)問題

組件A和組件B,組件B是個(gè)彈出框。
需求是點(diǎn)擊A里的某個(gè)按鈕,然后B組件才請求數(shù)據(jù)并彈出顯示B組件需要渲染的數(shù)據(jù)。
一般都會事先把B需要渲染的數(shù)據(jù)結(jié)構(gòu)在B里都寫好,以便B數(shù)據(jù)請求成功后渲染。
但是,當(dāng)A組件加載完成后,B組件其實(shí)還沒有請求數(shù)據(jù),不點(diǎn)擊按鈕加載B組件時(shí),在B組件寫好的數(shù)據(jù)不能用,會報(bào)變量未定義,或找不到。。。
這個(gè)時(shí)候有什么好的解決方案嗎?我可能會判斷數(shù)據(jù)存不存在(比如 response && response.data && response.data.list...)?但是有時(shí)候結(jié)構(gòu)很深,就很長,我想知道是不是我的解決思路有問題? 大家討論下啊

回答
編輯回答
愛礙唉

這個(gè)很簡單的!我就簡單寫一下!

import React, { Component } from 'react'; 
// B組件
import ComponentB from './ComponentB';

// A組件 
class ComponentA extends Component {
    constructor(props) {
        super(props);
        this.state = {
            aData: ''
        };
    }
    componentDidMount() {
        // 其他操作
    }
    async openModal() { // 打開彈窗
        const res = await ...; // 利用async await請求數(shù)據(jù),具體按照自己的
        this.setState({
            aData: res
        });
    }
   
    render() {
        const { aData } = this.state;
        return (
            <div className='my-container'>
                <div onClick={()=>this.openModal()}>打開彈窗</div>
                { aData ? <ComponentB aData={aData} /> : null }
            </div>
        )
    }
}

export default ComponentA;
2017年11月19日 10:20
編輯回答
終相守

render函數(shù)中,添加條件判斷,必須得條件滿足之后才進(jìn)行渲染。具體的渲染邏輯中,做好數(shù)據(jù)的兼容性處理(如不存在,或者默認(rèn)值等)

{xxx && xxx.xxx && xxx.xxx.xxx &&
    <div>{xxx.xxx.xxx}</div>
}
2018年1月11日 23:12
編輯回答
毀與悔

使用 lodashget 方法來判斷數(shù)據(jù)是否已經(jīng)存在,可以簡單點(diǎn)。。

2018年2月16日 16:16