React生命周期
组件从被创建到挂载到页面中运行,再到组件不用时卸载的过程
生命周期的每个阶段总是伴随着一些方法调用,这些方法就是生命周期的钩子函数
挂载时
constructor->render->componentDidMonunt
可以在componentDidMonunt中发送网络请求或者进行dom操作
更新时
render -> componentDidUpdate
什么时候触发更新
1.有新的props传入时
2.setState方法被调用(组件本身的setState方法)
3.forceUpdate(强制重新渲染)执行
可以在componentDidUpdate中发送网络请求或者进行dom操作
但setState必须放置在if条件中
componentDidUpdate(preProps) {
// preProps 之前的值 this.props当前的值
if (preProps != this.props) {
this.setState((state, props) => {
return { }
})
}
}
卸载时
componentWillUnmount
一旦组件卸载就会调用该函数
另外,refs更新在render后且在componentDidMount和componentDidUpdate之前
React父组件渲染时对子组件的影响
function App() {
return (
<>
<Parent1 />
<Parent2 />
</>
)
}
class Parent1 extends React.Component {
state = {
count: 0,
name: '父组件1'
}
updateState = () => {
this.setState(state => {
return {
count: state.count + 1
}
})
}
render() {
console.log('父组件的render')
return (
<>
{this.state.count}<br />
<button onClick={this.updateState}>更新一下父组件1</button>
<Child1 name={this.state.name} />
<Child2 name={this.state.name} />
</>
)
}
}
class Parent2 extends React.Component {
state = {
count: 0,
name: '父组件2'
}
updateState = () => {
this.setState(state => {
return {
count: state.count + 1
}
})
}
render() {
console.log('父组件的render')
return (
<>
{this.state.count}<br />
<button onClick={this.updateState}>更新一下父组件2</button>
<Child1 name={this.state.name} />
<Child2 name={this.state.name} />
</>
)
}
}
class Child1 extends React.Component {
render() {
console.log(`${this.props.name}-子组件1 render`)
return (
<div>
子组件1
</div>
)
}
}
class Child2 extends React.Component {
render() {
console.log(`${this.props.name}-子组件1 render`)
return (
<div>
子组件2
</div>
)
}
}
let root = document.querySelector('#root')
ReactDOM.createRoot(root).render(<App />)
父组件的state的更新,会让其子组件和所有的子节点,发生更新
避免重复渲染
核心思想是
如果组件在更新时,内容没有发生变化,那么就不应该发生更新
如何解决
通过shouldComponentUpdate
shouldComponentUpdate会在更新渲染前进行判断
在更新时在render之前会触发
具体代码
shouldComponentUpdate(nextProps, nextState) {
console.log('当前的state', nextState, '之前的state', this.state)
return nextState.count !== this.state.count
}