关于React父组件数据更新传入子组件的数据不是最新的解决方法

发布时间 2023-04-11 15:11:47作者: 马铃薯头抽雪茄

利用  componentWillReceiveProps

再子组件加入componentWillReceiveProps 当props跟新时就会触发此函数 那就可以再这里判断 当需要变更的数据变化时复制进去就可以了

componentWillReceiveProps(nextProps) {// 第一个参数代表即将传入的新的Props
    // 在这里我们仍可以通过this.props来获取旧的外部状态
    // 通过新旧状态的对比,来决定是否进行其他方法
    if (this.props.NewVariants !== nextProps.NewVariants) { // 判断上一次的porps的值和最新值是否不同然后变化
      this.setState({
        variants: nextProps.NewVariants,
      });
    }
  }