React的render不是纯函数? triggering nested component updates from render is not allowed

2 篇文章 0 订阅

“Warning: Render methods should be a pure function of props and state; triggering nested component updates from render is not allowed. If necessary, trigger nested updates in componentDidUpdate. ”

这里提供一种排查方案:这个问题可能会在开发环境中才会出现,如果你的项目中使用了mobx,并且在render中使用了computed,请检查render函数中所使用的computed函数中是否意外执行了副作用。如果有,请放在reaction或者autorun中执行。
警告截图
今天看一个项目的过程中,程序意外报了个render不是纯函数的警告,但是我没有发现在render中执行了副作用,这个警告让我困惑了两天,把我给整神了。

什么是副作用? 类似DOM操作,修改状态等等。

随便举个例子:

@computed get isStringArrEmpty() {
	//类似dom操作都是副作用,或者修改了当前mobx中某个observable的值
    const h2 = document.querySelector("h2");
    if (h2) {
      if (h2.getAttribute("class")) {
        h2.removeAttribute("class");
      } else {
        h2.setAttribute("class", "hide");
      }
    }
    return this.stringArr.length > 0;
  }

把副作用放在reaction即可解决:

@computed get isStringArrEmpty() {
    return this.stringArr.length > 0;
  }
  reaction(
  	()=>this.isStringArrEmpty,
  	(isStringArrEmpty)=>{
  		//副作用放在这里完美解决
	    const h2 = document.querySelector("h2");
	    if (h2) {
	      if (h2.getAttribute("class")) {
	        h2.removeAttribute("class");
	      } else {
	        h2.setAttribute("class", "hide");
	      }
	    }
  	}
  )
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值