反应:为什么道具没有冻结? [英] React: Why are props not frozen?
问题描述
反应建议不要变异道具.我当时的印象是,传递道具时,道具将是不可变的或冻结的.
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.