React既在constructor内部写state又在外部写了state的情况下,state到底是里面生效还是外面生效,
查了一下,没有说这俩同时的帖子,所以自己验证的时候第一个想法是考虑代码的顺序,还有constructor的特殊性
看了一下react的生命周期勾子,新旧都是constructor排在第一位,
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210427084016567.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1ZvaWNldQ==,size_16,color_FFFFFF,t_70)
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210427084032362.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1ZvaWNldQ==,size_16,color_FFFFFF,t_70)
下面验证阶段:
1.只有外部有state的时候,有一个就不说了,直接就赋值了,讨论有两个会不会覆盖
export default class Line extends Component {
state={
count:1,
// num:33
}
state={
count:2,
num:44
}
onClick=()=>{
console.log('点我后', this.state);
}
render() {
console.log('render后', this.state);
return (
<div>
<button onClick={this.onClick}>dianwo </button>
</div>
)
}
}
结果显示的是第二次state={}的内容,说明能够多次执行
![在这里插入图片描述](https://img-blog.csdnimg.cn/2021042708424815.png)
调换一下,在第一次state里放两个,第二次只放一个,看是否是全部覆盖,还是只修改同一个键的内容,如下
如果是全覆盖,那么输出的就不会有num,如果只是覆盖相同内容,那么应该是{count:2,num:33}
state={
count:1,
num:33
}
state={
count:2,
// num:44
}
结果如下,说明会全部覆盖,而不是像setState一样只修改相同的键,
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210427084626704.png)
2.同理验证这两种情况在constructor里的结果
export default class Line extends Component {
constructor(props){
console.log('constructor');
super(props)
// 初始化状态
this.state={
count:0
}
this.state={
count:3,
num:55
}
}
onClick=()=>{
console.log('点我后', this.state);
}
render() {
console.log('render后', this.state);
return (
<div>
<button onClick={this.onClick}>dianwo </button>
</div>
)
}
}
可知为 可多次执行
![在这里插入图片描述](https://img-blog.csdnimg.cn/2021042708521316.png)
constructor(props){
console.log('constructor');
super(props)
// 初始化状态
this.state={
count:0,
num:66
}
this.state={
count:3,
// num:55
}
}
可知为 全覆盖
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210427085314586.png)
在单独的情况下,两者均是以最后一次state为准
下面是两者都存在的情况的验证:
3.考虑代码顺序
如果是按照代码顺序来的,那么最后是constructor里的第二个state生效
state={
count:1,
num:33
}
constructor(props){
console.log('constructor');
super(props)
// 初始化状态
this.state={
count:0,
num:66
}
this.state={
count:3,
// num:55
}
}
结果是这样的,但是不能完全证明,有可能是constructor的特殊性,因为生命周期中,constructor是首先运行的
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210427085624131.png)
所以换个顺序测试,如果真是按顺序,那么应该是最后一个state,count为2,num为44
constructor(props){
console.log('constructor');
super(props)
// 初始化状态
this.state={
count:0,
num:66
}
this.state={
count:3,
// num:55
}
}
state={
count:2,
num:44
}
结果只有count为3,是constructor里的第二个,说明不是按顺序来的,可见不管constructor在state={}的前后,只要在constructor里写了state,就不会再执行外部的state了,并且以constructor里最后一次this.state={ }为准
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210427085844605.png)
总结
-
初始化state与setState不同,多次初始化state={}或者constructor里this.state={},都会全部覆盖,而不是像setState的覆盖相同部分键值对;
-
单独在同一个区域中所写的多次state(constructor内部,和外部两个区域),以最后一次为准,即代码顺序,而且是全覆盖;
- constructor中初始化state权重最高,并且会覆盖外部所写,即外部无法生效(不管代码顺序)