React?component.forceUpdate()強制重新渲染方式
component.forceUpdate()強制重新渲染
component.forceUpdate()
一個不常用的生命周期方法,它的作用就是強制刷新
官網(wǎng)解釋如下
默認情況下,當組件的 state 或 props 發(fā)生變化時,組件將重新渲染。
如果 render() 方法依賴于其他數(shù)據(jù),則可以調(diào)用 forceUpdate() 強制讓組件重新渲染。
調(diào)用 forceUpdate() 將致使組件調(diào)用 render() 方法,此操作會跳過該組件的 shouldComponentUpdate()。
但其子組件會觸發(fā)正常的生命周期方法,包括 shouldComponentUpdate() 方法。
如果標記發(fā)生變化,React 仍將只更新 DOM。
通常你應該避免使用 forceUpdate(),盡量在 render() 中使用 this.props 和 this.state。
通常來說
我們應該用 setState() 更新數(shù)據(jù),從而驅(qū)動更新。
所以用到 component.forceUpdate() 的情況并不多
class App extends React.Component {
constructor(props) {
super(props);
console.log("constructor")
this.onClickHandler = this.onClickHandler.bind(this);
}
componentWillMount() {
console.log("componentWillMount")
}
componentDidMount() {
console.log("componentDidMount")
}
componentWillUnmount() {
console.log("componentWillUnmount")
}
componentWillReceiveProps() {
console.log("componentWillReceiveProps")
}
shouldComponentUpdate() {
console.log("shouldComponentUpdate")
return true
}
componentWillUpdate() {
console.log("componentWillUpdate")
}
componentDidUpdate() {
console.log("componentDidUpdate")
}
onClickHandler() {
console.log("onClickHandler")
this.forceUpdate();
}
render() {
console.log("render")
return (
<button onClick={this.onClickHandler}> click here </button>
);
}
}
ReactDOM.render(<App />,
document.getElementById("react-container")
);
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
React使用setState更新數(shù)組的方法示例(追加新數(shù)據(jù))
在?React?中,setState?是管理組件狀態(tài)的核心方法之一,然而,當我們需要更新狀態(tài)中的數(shù)組時,如何高效且安全地操作變得尤為關(guān)鍵,本文將詳細解析以下代碼的實現(xiàn)邏輯,幫助你掌握在?React?中追加數(shù)組數(shù)據(jù)的最佳實踐,需要的朋友可以參考下2025-03-03
react中如何對自己的組件使用setFieldsValue
react中如何對自己的組件使用setFieldsValue問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-03-03

