React 生命周期componentWillReceiveProps未触发的坑

今天在开发中遇到的坑,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 有待深入研究...

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容