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

鍍金池/ 問答/HTML/ redux實(shí)際應(yīng)用問題

redux實(shí)際應(yīng)用問題

class PhotoList{
    componentDidMount(){
        if(this.props.photos){// 如果redux中沒有photos
            this.props.actions.getPhotos() // 異步請(qǐng)求
        }
    }
}
export connect(..)(UserHeader)

class App {
    render(){
        return <div>
            <PhotoList/>
            <PhotoChooser/>
        </div>
    }
}

假如PhotoChooser,需要photo

class PhotoChooser{
    componentDidMount(){
        const {actions,photos}=this.props
        actions.SetCurrentPhoto(photos[0]) // 設(shè)置第一個(gè)為默認(rèn)的currentPhoto
    }
}

這些寫得有問題,假如第一次請(qǐng)求該頁(yè)面,redux中沒有Photos(此時(shí)PhotoList正在請(qǐng)求),那么就無(wú)法設(shè)置默認(rèn)的currentPhoto
所以要搞成這樣

class PhotoChooser{
    componentDidMount(){
        const {actions,photos}=this.props
        if(photos){
            actions.SetCurrentPhoto(photos[0]) // 設(shè)置第一個(gè)為默認(rèn)的currentPhoto
        }
    }
    componentWillReceiveProps(nextProps){
        const {currentPhoto,photos}=this.props
        if(!currentPhoto&&photos){
            actions.SetCurrentPhoto(photos[0])
        }
    }
}

componentDidMount仍然要保留,因?yàn)殇秩驹摻M件時(shí),redux中也可能已經(jīng)有photos(在前文例子中不會(huì)有這個(gè)情況,但是實(shí)際場(chǎng)景很可能會(huì)出現(xiàn)這個(gè)情況),此時(shí)只有componentDidMount會(huì)調(diào)用
如果redux中沒有photos,那么PhotoList會(huì)發(fā)出請(qǐng)求,而PhotoChooser就在componentWillReceiveProps等待photos

問題:
在使用redux后,尤其是把異步請(qǐng)求放到redux后,componentWillReceiveProps必須要寫一些邏輯
我想知道,這是不可避免的嗎?有沒有更好的寫法

回答
編輯回答
浪蕩不羈

建議同一個(gè)redux的state傳入兩個(gè)組件,在PhotoListactions.getPhotos()調(diào)完后直接設(shè)置currentPhoto, 這樣PhotoChooser組件直接就會(huì)更新。

2017年3月12日 17:37