类组件的生命周期
javascript
import React, { Component } from 'react'
export default class learnReact05 extends Component {
state = {
number: 1
}
render() {
return (
<div>{this.state.number}</div>
)
}
// 一般将请求的方法,放在这个生命周期
componentDidMount() {
setInterval(() => {
this.setState({
number: this.state.number + 1
})
}, 1000)
}
// 更新阶段 =>组件卸载
componentWillUnmount(){
console.log('卸载');
}
}
组件性能优化
06的代码
javascript
import React, { Component } from 'react'
import LearnReact07 from './learnReact07'
export default class learnReact06 extends Component {
state = {
arr: ['组件1', '组件2', '组件3', '组件4'],
number: 0
}
render() {
return (
<div>
<input type="number" value={this.state.number} onChange={this.changeNumber} />
<div>{this.state.number}</div>
{
this.state.arr.map((item, index) => {
return <LearnReact07 key={index} item={item} index={index} changeMsg={this.changeMsg} />
})
}
</div>
)
}
changeMsg = (index) => {
const arr = [...this.state.arr]
arr[index] = '哈哈哈哈'
this.setState({
arr: arr
})
}
changeNumber = (e) => {
this.setState({
number: e.target.value
})
}
}
07的代码
javascript
import React, { Component } from 'react'
export default class learnReact07 extends Component {
shouldComponentUpdate = (nextProps, nextState) => {
return nextProps.item != this.props.item
}
render() {
// console.log('子组件是否触发');
return (
<div>
<h1>{this.props.item}</h1>
<button onClick={() => {
this.props.changeMsg(this.props.index)
}}>点击我改变嗷</button>
</div>
)
}
}
结语
到此类组件已经全部完成学习,通常类组件在工作中不是经常使用,接下来要开启函数组件的学习。不断的强化自己,让自己可以在前端领域不断提升自己。