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).
(使用顶级React.render
可以实现,但是在组件内不起作用(这是有道理的,因为render
方法仅返回一个对象)。)
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).
(在内部单击按钮会调用this.render()
,但这实际上并不是导致渲染发生的原因(您可以看到实际情况,因为{Math.random()}
创建的文本不会更改)。)
However, if I simply call this.setState()
instead of this.render()
, it works fine. (但是,如果我只是简单地调用this.setState()
而不是this.render()
,它就可以正常工作。)
So I guess my question is: do React components need to have state in order to rerender?
(所以我想我的问题是: React组件是否需要具有状态才能重新渲染?)
Is there a way to force the component to update on demand without changing the state? (有没有一种方法可以在不更改状态的情况下强制组件按需更新?)
ask by Philip Walton translate from so 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…