账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    redux实际应用问题
    48
    0
    class PhotoList{
        componentDidMount(){
            if(this.props.photos){// 如果redux中没有photos
                this.props.actions.getPhotos() // 异步请求
            }
        }
    }
    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]) // 设置第一个为默认的currentPhoto
        }
    }

    这些写得有问题,假如第一次请求该页面,redux中没有Photos(此时PhotoList正在请求),那么就无法设置默认的currentPhoto
    所以要搞成这样

    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仍然要保留,因为渲染该组件时,redux中也可能已经有photos(在前文例子中不会有这个情况,但是实际场景很可能会出现这个情况),此时只有componentDidMount会调用
    如果redux中没有photos,那么PhotoList会发出请求,而PhotoChooser就在componentWillReceiveProps等待photos

    问题:
    在使用redux后,尤其是把异步请求放到redux后,componentWillReceiveProps必须要写一些逻辑
    我想知道,这是不可避免的吗?有没有更好的写法

    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部