Thursday 21 December 2017

reactjs - Can you force a React component to rerender without calling setState?

itemprop="text">

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 (

{Math.random()}
onClick={this.handleButtonClick.bind(this)}>
Click me



)


}
}


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?


itemprop="text">
class="normal">Answer



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




Documentation: href="https://facebook.github.io/react/docs/react-component.html#forceupdate"
rel="noreferrer">https://facebook.github.io/react/docs/component-api.html



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...