反应:为什么道具没有冻结? [英] React: Why are props not frozen?

查看:69
本文介绍了反应:为什么道具没有冻结?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

反应建议不要变异道具.我当时的印象是,传递道具时,道具将是不可变的或冻结的.

React suggests not to mutate props. I was operating under the impression that when props are passed in, they would be immutable or frozen.

下面的代码不会引发任何错误,并且会更改道具.这是一个错误吗?

The code below does not throw any errors and mutates the prop. Is this a bug?

try{
  var a = this.props.a;
  a.push('one')
  a.push('two')
  a.push('three')
  console.log(a)
}catch(err){
  console.log(err)
}

推荐答案

我不确定其背后的确切原因,或者是否有记录在案,但我可以猜测一下:

I'm not sure of the exact reasoning behind it or if that's documented somewhere but I could take a guess:

冻结变量的任何分配都不容易,甚至在使用新颖的浏览器或什至未实现的浏览器功能之外也不一定可行.另外,冻结应用程序中的所有道具可能会对性能产生影响,并且肯定需要将其删除以进行产品构建.

Freezing any assignment to a variable is not easy or even necessarily possible outside of using new-ish or even as of yet unimplemented browser features. Also deep freezing all your props in your app could have performance implications and would certainly need to be removed for prod builds.

您可以冻结原始变量的分配吗? 我不这样认为.我认为babel使用const通过在编译时静态检查代码来做到这一点.

Can you freeze assignment of a primitive variable? I don't think so. I think babel does it with const by statically checking code at compile time.

并且您可以在没有Object.freeze或ES7代理的情况下冻结对象吗? 同样,我不这么认为,

您可能无法在旧版引擎中获得的

which you cannot possibly obtain in legacy engines

如果某人做了某些突变怎么办? 这些道具是浅复制的,这意味着除非修改嵌套对象,否则不会影响父道具.但是,即使您这样做也不会影响应用程序,因为这将在下一次渲染时消失(就像您所做的修改一样).

What if someone does mutate something? These props are shallow copied, meaning you won't affect the parent prop unless you modify a nested object. However even if you did it would't affect the app, as that would get wiped out on the next render (just like your modifications).

如果我出错了,请告诉我!这只是我的理由.

If I got something wrong please let me know! This is just my reasoning.

这篇关于反应:为什么道具没有冻结?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆