在shouldComponentUpdate这个生命周期函数中,分别打印this.state和this得到的结果中state中的值是不同的,这是为什么?
代码如下:
import React, { Component } from "react";
class Test extends Component {
constructor(props) {
super(props);
this.state = {
num: 0
};
this.handleClick = this.handleClick.bind(this);
}
shouldComponentUpdate(nextProps, nextState) {
console.log("this.state = ", this.state);
console.log(this);
return false;
}
render() {
console.log("this.state = ", this.state);
return (
<div>
<button onClick={this.handleClick}>click</button>
</div>
);
}
handleClick() {
this.setState({
num: this.state.num + 1
});
}
}
应该是因为第二次打印后,this.state 的值发生了变化,因此打印出来的值也跟着变化了,你可以对需要打印的对象进行深拷贝后再打印出来,这样打印出来的值就和打印瞬间的值是一样的。
不过如何对 React 的实例进行深拷贝这个问题我还没有研究过,反正 JSON 是做不来的。