Practical Application of redux

class PhotoList{
    componentDidMount(){
        if(this.props.photos){// reduxphotos
            this.props.actions.getPhotos() // 
        }
    }
}
export connect(..)(UserHeader)

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

if PhotoChooser, needs photo

class PhotoChooser{
    componentDidMount(){
        const {actions,photos}=this.props
        actions.SetCurrentPhoto(photos[0]) // currentPhoto
    }
}

these are problematic. If the page is requested for the first time, there is no Photos in the redux (PhotoList is requesting it at this time), then the default currentPhoto
cannot be set, so do it like this

.
class PhotoChooser{
    componentDidMount(){
        const {actions,photos}=this.props
        if(photos){
            actions.SetCurrentPhoto(photos[0]) // currentPhoto
        }
    }
    componentWillReceiveProps(nextProps){
        const {currentPhoto,photos}=this.props
        if(!currentPhoto&&photos){
            actions.SetCurrentPhoto(photos[0])
        }
    }
}

componentDidMount should still be retained, because when rendering the component, there may already be photos in redux (this will not be the case in the previous example, but this is likely to happen in the actual scenario), and only componentDidMount will call
if there is no photos, in redux, PhotoList will make a request, and PhotoChooser will wait for photos in componentWillReceiveProps

.

question:
after using redux, especially after putting asynchronous requests into redux, componentWillReceiveProps must write some logic
I wonder, is this inevitable? Is there a better way to write

Mar.11,2021

suggests that two components of the same redux should be passed in. After actions.getPhotos () of PhotoList is adjusted, set currentPhoto directly, so that the PhotoChooser component will be updated directly.

Menu