Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

reactjs - 您可以在不调用setState的情况下强制React组件重新渲染吗?(Can you force a React component to rerender without calling setState?)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In your component, you can call this.forceUpdate() to force a rerender.

(在您的组件中,可以调用this.forceUpdate()强制重新渲染。)

Documentation: https://facebook.github.io/react/docs/component-api.html

(文档: https : //facebook.github.io/react/docs/component-api.html)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...