繁体   English   中英

当扩展props时reactjs的this.props正在变异

[英]this.props of reactjs is mutating when the props are extended

我正在尝试使用lodash的_.extend方法扩展道具并将其分配给新变量。 但这正在改变this.props的价值

var Component = React.createClass({
   render: function () {
      var newProps = _.extend(this.props, {b: 2, c: 3});
      console.log(this.props, newProps);
      return <div> hello world </div>
   }
});

React.render(<Component a={1} b={2} />, document.body);

在上面的示例中,为this.props和newProps都将{a:1,b:2:c:3}打印到控制台中

但是期望值为:this.props = {a:1,b:2}和newProps = {a:1,b:2,c:3}

我想念什么吗?

_.extend修改第一个参数,并返回它。 为了避免发生突变,您应该将空对象或默认对象作为第一个参数传递。

var newProps = _.extend({}, this.props, {b: 2, c: 3});

我建议使用常规名称_.assign(扩展名是别名)。 更清楚的是它的作用,并与es6的Object.assign相匹配。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM