React component.forceUpdate() 强制重新渲染

1,134 阅读1分钟

component.forceUpdate() 一个不常用的生命周期方法, 它的作用就是强制刷新

官网解释如下

默认情况下,当组件的 state 或 props 发生变化时,组件将重新渲染。如果 render() 方法依赖于其他数据,则可以调用 forceUpdate() 强制让组件重新渲染。 调用 forceUpdate() 将致使组件调用 render() 方法,此操作会跳过该组件的 shouldComponentUpdate()。但其子组件会触发正常的生命周期方法,包括 shouldComponentUpdate() 方法。如果标记发生变化,React 仍将只更新 DOM。 通常你应该避免使用 forceUpdate(),尽量在 render() 中使用 this.props 和 this.state。

通常来说, 我们应该用 setState() 更新数据,从而驱动更新.所以用到 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")
);

end