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

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

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

回答
編輯回答
愛(ài)礙唉

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

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() { // 打開(kāi)彈窗
        const res = await ...; // 利用async await請(qǐng)求數(shù)據(jù),具體按照自己的
        this.setState({
            aData: res
        });
    }
   
    render() {
        const { aData } = this.state;
        return (
            <div className='my-container'>
                <div onClick={()=>this.openModal()}>打開(kāi)彈窗</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 方法來(lái)判斷數(shù)據(jù)是否已經(jīng)存在,可以簡(jiǎn)單點(diǎn)。。

2018年2月16日 16:16