对于类组件而言
- state发生变化,props发生变化,强制更新this.forceUpdate()。
- 只要使用setState就会触发重新渲染(re-render),即使setState返回一样的引用。下方代码块,点击annuity,并没有修改num的值,但是会触发重新渲染。
export class Ev extends React.Component(){
constructor(){
this.state={
num:0
}
}
render(){
console.log("组件刷新")
return(
<div>
<button onClick={()=>{
// 只是使用了setState,并不修改num的值
this.setState({num:this.state.num})
}}>button1</button>
</div>
)
}
}
- 这个问题可能会接着提问PureComponent PureComponent在更新在前会做一层浅比较,引用类型内部发生的变化并不会检测出来。 Component可以在shouldComponentUpdate(性能优化)里面进行判断来实现PureComponent
对于函数组件
任何情况下都会重新渲染,没有生命周期,官方提供React.memo()的优化手段。
渲染中发生错误
可以使用错误边界来捕获错误。(渲染时候的错误)
ErrorBoundary 错误会在componentDidCatch中被捕获。
react请求应该在什么时候调用
请求应该在componentDidMount操作中