React 生命周期
- react生命周期一定要知道,写了常用的周期
父子组件的生命周期
创建
生命周期:constructor
生命周期:render
List生命周期:constructor
List生命周期:render
List生命周期:componentDidMount
生命周期:componentDidMount
更新
生命周期:shouldComponentUpdate
生命周期:render
List生命周期:shouldComponentUpdate
List生命周期:render
List生命周期:componentDidUpdate
生命周期:componentDidUpdate
import React from 'react'
class Input extends React.Component{
constructor(props) {
super(props);
this.state = {
title:''
}
}
render() {
return <>
<input value={this.state.title} onChange={this.changeHandler}/>
<button onClick={this.onSubmit}>提交</button>
</>
}
changeHandler = (e) =>{
this.setState({
title: e.target.value
})
}
onSubmit = () =>{
this.props.submitTitle(this.state.title)
this.setState({
title:''
})
}
}
class List extends React.Component{
constructor(props) {
console.log('List生命周期:constructor')
super(props);
}
render() {
console.log('List生命周期:render')
return (<ul>
{this.props.list.map((item,index) =>{
return <li key={index}>{item.title}</li>
})}
</ul>)
}
componentDidMount() {
console.log('List生命周期:componentDidMount')
}
componentDidUpdate(prevProps, prevState, snapshot) {
console.log('List生命周期:componentDidUpdate')
}
componentWillUnmount() {
console.log('List生命周期:componentWillUnmount')
}
shouldComponentUpdate(nextProps, nextState, nextContext) {
console.log('List生命周期:shouldComponentUpdate')
if (nextProps.list.length === 3){
return false
}
return true
}
}
class Basics06 extends React.Component{
constructor(props) {
console.log('生命周期:constructor')
super(props);
this.state = {
list:[
{
title:'xxx'
}
]
}
}
render() {
console.log('生命周期:render')
return (
<>
<pre>{JSON.stringify(this.state.list)}</pre>
<Input submitTitle={this.onSubmitTitle}></Input>
<List list={this.state.list}></List>
</>
)
}
onSubmitTitle = (title) =>{
this.setState({
list:this.state.list.concat([{title}])
})
}
componentDidMount() {
console.log('生命周期:componentDidMount')
}
componentDidUpdate(prevProps, prevState, snapshot) {
console.log('生命周期:componentDidUpdate')
}
componentWillUnmount() {
console.log('生命周期:componentWillUnmount')
}
shouldComponentUpdate(nextProps, nextState, nextContext) {
console.log('生命周期:shouldComponentUpdate')
return true
}
}
export default Basics06