组件状态数据的定义和更新
setState(),异步处理函数
import React, { Component } from 'react'
export default class Login extends Component {
name = '花花';
constructor(){
super()
// 在state中专门存放状态数据
this.state = {
newName:'张碧晨'
}
}
handler(msg){
// this.state.newName = msg;
// console.log(this.state);
// setState: 修改状态的数据,并且成功的再次渲染搭配视图中
// setState是异步函数,如果想要获取最新的更新数据,需要在第二个参数中,进行接收
this.setState({newName:msg},()=>{
console.log(this.state);
})
}
render() {
// console.log(this.state);
const {newName} = this.state;
return (
<div>
<h1>{this.name}</h1>
<h2>{this.state.newName}</h2>
{/* 简写: */}
<h2>{newName}</h2>
<hr/>
<button onClick={()=>this.handler('邓紫棋')}>邓紫棋</button>
</div>
)
}
}