美文网首页React
React 生命周期componentWillReceivePr

React 生命周期componentWillReceivePr

作者: Evan_zhan | 来源:发表于2017-09-05 16:26 被阅读50次

    今天在开发中遇到的坑,redux提交一个action改变一个state后,拿到新的props.images(数组)。 发现没有触发componentWillReceiveProps 半天没查到是什么原因,还好最后在带我进react的大牛,肖大哥的帮忙下找到了原因。
    记录下来,希望帮到很多新进react坑的小伙伴

    贴代码~~

        ConsultService.deleteImages({
          uploadId: data.uploadId,
          imageId: data.imageId,
          casesId: this.props.casesId
        }).then((data) => {
        // redux中取得images
        let newList = this.props.images;
        newList.splice(index, 1);
        this.setState({
          images: newList
        },()=>{
          const { imagesAction } = this.props;
          imagesAction.changeImages(this.state.images)
          console.log(this.props.images)
        })
    })
    

    这里提交一个action ,因此组件会从redux中接收到新的props.images.可是发现并没有触发componentWillReceiveProps.
    原因是因为在react中,不是根据数据内容变化来判断是否变化,而是根据数据的引用是否变化。而这里this.props.images是一个数组,数组内容发生变化,可是引用没变,所以react认为它没变

    解决办法

    new一个数组,改变数组的引用

     const { imagesAction } = this.props;
     const arr = [];
     arr.concat(this.state.images);
     imagesAction.changeImages(arr)
     console.log(this.props.images)
    

    这样就可以了。是react中比较坑的一个地方。

    具体react为什么有这种机制?

    mark 有待深入研究...

    相关文章

      网友评论

      本文标题:React 生命周期componentWillReceivePr

      本文链接:https://www.haomeiwen.com/subject/rtzujxtx.html