本文介绍了你能在不调用 setState 的情况下强制 React 组件重新渲染吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个外部的(组件的)可观察对象,我想监听它的变化.当对象更新时,它会发出更改事件,然后我想在检测到任何更改时重新渲染组件.
使用顶级 React.render
这已经是可能的,但是在组件中它不起作用(这是有道理的,因为 render
方法只是返回一个对象).
这是一个代码示例:
导出默认类 MyComponent extends React.Component {处理按钮点击(){this.render();}使成为() {返回 (<div>{Math.random()}<button onClick={this.handleButtonClick.bind(this)}>点击我按钮>
)}}
在内部点击按钮会调用 this.render()
,但这并不是真正导致渲染发生的原因(您可以看到这一点,因为 {Math.random 创建的文本()}
不会改变).但是,如果我只是调用 this.setState()
而不是 this.render()
,它工作正常.
所以我想我的问题是:React 组件需要有状态才能重新渲染吗?有没有办法强制组件按需更新而不改变状态?
解决方案
在类组件中,您可以调用 this.forceUpdate()
强制重新渲染.
文档:https://facebook.github.io/react/docs/component-api.html
在函数组件中,没有与 forceUpdate
等效的内容,但您可以设计一种方法来强制更新useState
钩子.
I have an external (to the component), observable object that I want to listen for changes on. When the object is updated it emits change events, and then I want to rerender the component when any change is detected.
With a top-level React.render
this has been possible, but within a component it doesn't work (which makes some sense since the render
method just returns an object).
Here's a code example:
export default class MyComponent extends React.Component {
handleButtonClick() {
this.render();
}
render() {
return (
<div>
{Math.random()}
<button onClick={this.handleButtonClick.bind(this)}>
Click me
</button>
</div>
)
}
}
Clicking the button internally calls this.render()
, but that's not what actually causes the rendering to happen (you can see this in action because the text created by {Math.random()}
doesn't change). However, if I simply call this.setState()
instead of this.render()
, it works fine.
So I guess my question is: do React components need to have state in order to rerender? Is there a way to force the component to update on demand without changing the state?
解决方案
In class components, you can call this.forceUpdate()
to force a rerender.
Documentation: https://facebook.github.io/react/docs/component-api.html
In function components, there's no equivalent of forceUpdate
, but you can contrive a way to force updates with the useState
hook.
这篇关于你能在不调用 setState 的情况下强制 React 组件重新渲染吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!