美文网首页
getDerivedStateFromProps的大坑

getDerivedStateFromProps的大坑

作者: 玖肆seven | 来源:发表于2021-02-01 15:07 被阅读0次

    我的需求是这样的:
    点击一个编辑按钮
    弹出一个内容为表单的弹窗
    编辑是要回填表单的
    这个没问题
    在弹窗组件用这个生命周期:

    //modalInfo即填入表单的值
    state = {
       data:{}
    }
    static getDerivedStateFromProps(nextProps,prevState) {
        if(nextProps.modalInfo.id !== prevState.handworkData.id){
          const { modalInfo } = nextProps;
          return {
            data:modalInfo    // render里面拿到映射后的data渲染即可
          }
        }
        return null;
      }
    

    But,当弹窗弹出来的时候,我不仅仅想要实现回填,还需要调接口拿到一个list,怎么搞呢?在这里面怎么直接调用方法?this.function()?nonono~
    这里要注意getDerivedStateFromProps是静态方法不能用this直接调用组件中的方法
    那我就去百度了,到底要怎么写嘛
    直接贴下好使的代码吧

    //modalInfo即填入表单的值
    state = {
       data:{}
    }
    static getDerivedStateFromProps(nextProps,prevState) {
        if(nextProps.modalInfo.id !== prevState.handworkData.id){
          const { modalInfo } = nextProps;
          const {state, city} = nextProps.modalInfo.receiverInfo;
          new 当前组件名字(nextProps).handleAddressChangeCity(state) // 对,就这么写
          new 当前组件名字(nextProps).handleAddressChangeArea(city) //对,就这么写
          return {
            data:modalInfo
          }
        }
        return null;
      }
    

    就是是new一个新的组件,让这个组件去调用组件中的方法
    这个方法解决我当前的需求没什么问题,但是百度的时候看到了另一种坑和解决方案
    贴一下,仅供参考

     this.state = {
          aGoods: [],
          cid:null,
          precid:null,
          num:1
    }
            this.sum=0;
         static getDerivedStateFromProps(newProps,preState)
        {
            new GoodsItems(newProps).change();
            return null;
          
        }
       change(){
           this.setState({
               num:2
           },()=>{
               console.log("num1: ",this.state.num)
           })
           this.sum=this.sum+1;
           console.log("num2: ",this.state.num)
           console.log("sum: ",this.sum)
        }
    
    
    image.png

    我们可以看到num1没输出,每次num2都是1和sum都是1,这是因为每次都是new了一个新的组件改变的是新组建的值,并不影响原来的组件,所以不能用来改变state的值。我不买关子了直接上解决方案。

    解决方案

    我们将子组件直接放到父组件上,不使用子路由,然后给子组件加上一个key指,每次子组件需要更新时就将key值改变,这样的话就相当于重新加载了一个新的子组件而不是仅仅去更新数据,我们看代码

    <div className={Css['goods-content']}>
       <GoodsItems aGoods={this.state.aGoods ? this.state.aGoods: ''} key={this.state.cid}/>
    </div>
    

    这里我们也可以将数据传入,子组件在mounted时候进行setState修改数据
    这是官网解释

    image.png
    本文参考链接:https://blog.csdn.net/weixin_43905830/article/details/108760828

    何以解忧 唯有学习

    相关文章

      网友评论

          本文标题:getDerivedStateFromProps的大坑

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