类组件的this指向问题
<body>
<div id="app"></div>
<script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script type="text/babel">
class Clock extends React,Component{
constructor(props){
super(props)this.state = {time:new Date().toLocalTimeString()}
//一次性this绑定
//go()函数=>新的函数 已经绑定this=>新的函数 赋值给this.go
this.go = this.go.bing(this)
//this.go = () =>{} //等同于
}
go(){
console.log(this) //this指向undefinned
this.setState(){
time:new Date().toLocalTimeString()
}
}
//es7新出的语法,es7新特性
go()=>{
console.log(this) //this指向组件实例
this.setState(){ time:new Date().toLocalTimeString() }
}
render(){
cosole.log(this) //生命周期里面的钩子函数中的this指向类的实例
return(
<div>
<h1>Clock</h1>
<h2>{ this.state.time }</h2>
{/* 0. this指向undefind*/}
<button onClick = { this.go }>Go1</button>
{/* 1. 报错:Maximum update depth exceeded
内存溢出 原因:render和执行函数互相调用 死循环*/}
<button onClick = { this.go() }>Go2</button> //直接执行
{/*2.箭头函数中的this指向render所在的作用域
问题2.1:函数是一个特殊对象,引用数据类型需要占用一个堆内
存空间,重复声明,重复开辟新的内存空间,内存相对较差
问题2.2:元素构件中添加了js逻辑代码,导致代码复杂,
臃肿,维护困难*/}
<button onClick = {
function(){console.log(this) //this指向undefined
this.setState(){
time:new Date().toLocalTimeString() }
}}>Go3-1</button>
<button onClick = {
()=>{this.setState(){
time:new Date().toLocalTimeString() }
}}>Go3-2</button>
{/*3.手动修改this指向,代码逻辑混乱问题得到解决
问题:重复绑定,重复生成新的函数,占内存空间,性能较差*/}
<button onClick = { this.go.bind(this) }>Go4</button>
{/*4.一次性绑定,再此阶段执行的时候this.go=>this(组件
实例)已经被绑定完成*/}
<button onClick = { this.go.bind(this) }>Go5</button>
{/*5.es7新特性*/}
<button onClick = { this.go.bind(this) }>Go6</button>
<button onClick = {
console.log(this) //this指向组件实例
()=>{React.unmountComponentAtNode(document.getElementById("app"))
} }>remove Component</button>
</div>
)
}
componentDidMount(){
cosole.log(this) //生命周期里面的钩子函数中的this指向类的实例
this.timeId = setInterval(()=>{
this.setState({time:new Date().toLocaleTimeString()
})
},1000)
}
componentWillUnmount(){
clearInterval(this.timerId)
}
}
var element = <Clock time = { new Date().toLocaleTimeString() }/>
ReactDOM.render(element,document.getElementById("app"))
</script>
</body>