变量的复制
第1次编辑
要讨论的问题并非完全react相关,而是原生js的一个概念,只不过在应用react的场景下,经常涉及state和props的复制,因而有一些只得思考的地方。
5 class Simple extends React.Component {
6 state = {
//== wrong ==
7 // arr : Object.create(this.props.arr)
8 // arr: this.props.arr
//== right ==
9 // arr : _.clone(this.props.arr, true)
10 arr : _.cloneDeep(this.props.arr)
11 }
12 changeState() {
13 this.setState({
14 arr: this.state.arr.map((item) => { item.val = item.val + 1 ; return item;})
15 });
16 }
17 render() {
18 return (
19 <div>
20 <div onClick={this.changeState.bind(this)}>change</div>
21 <div>props: { this.props.arr.map((item) => item.val) } </div>
22 <div>state: { this.state.arr.map((item) => item.val) } </div>
23 </div>
24 );
25 }
26 }
27
28 ReactDOM.render(<Simple arr={[{val: 1}, {val: 2}, {val: 3}]}/>, document.getElementById('component-example-simple'));
以下几种构造对象的方式值得深究:
b = new Object(a);
b = Object.create(a);
b = _.clone(a);
b = _.cloneDeep(a);