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

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

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值