Javascript 立即使用 react.js 强制重新渲染(更新状态并更新 DOM)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30838602/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Force a re-render (update the state and update the DOM) immediately with react.js
提问by tjhance
I realize that calling setStatedoes not update this.stateimmediately, nor does it immediately call renderand refresh the DOM. The docs say
我意识到调用setState不会this.state立即更新,也不会立即调用render和刷新 DOM。文档说
setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.
There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.
setState() 不会立即改变 this.state 而是创建一个挂起的状态转换。调用此方法后访问 this.state 可能会返回现有值。
无法保证对 setState 调用的同步操作,并且可能会批量调用以提高性能。
I would like to be able to force a "state transition" like this at any point. This seems like it ought to be a fairly natural operation, but I can't find any mention of it in the docs. Is there a way to do it?
我希望能够在任何时候强制执行这样的“状态转换”。这似乎应该是一个相当自然的操作,但我在文档中找不到任何提及。有没有办法做到这一点?
回答by Colin Ramsay
You can use forceUpdatefor this:
您可以forceUpdate为此使用:
If your render() method reads from something other than this.props or this.state, you'll need to tell React when it needs to re-run render() by calling forceUpdate(). You'll also need to call forceUpdate() if you mutate this.state directly.
如果你的 render() 方法读取的不是 this.props 或 this.state,你需要通过调用 forceUpdate() 来告诉 React 什么时候需要重新运行 render()。如果您直接改变 this.state,您还需要调用 forceUpdate()。
https://facebook.github.io/react/docs/component-api.html#forceupdate
https://facebook.github.io/react/docs/component-api.html#forceupdate
回答by lonewarrior556
You can use a forceUpdatein conjunction with having a key on the top level component as so..
您可以将 aforceUpdate与顶级组件上的键结合使用,这样..
let key= 0;
var Hello = React.createClass({
sudoForceUpdate(){
key++;
this.forceUpdate();
},
render: function(){
return <div key={key}>Example</div>;
}
});
By editing the key and forcing an update, the dom will always rerender.
通过编辑密钥并强制更新,dom 将始终重新渲染。
Here is an example that highlights the difference between just a force edit, and one with a key change*.
这是一个示例,突出显示了仅强制编辑和键更改之间的区别*。
https://jsfiddle.net/69z2wepo/82763/
https://jsfiddle.net/69z2wepo/82763/
*note that this is likely pretty bad practice.
*请注意,这可能是非常糟糕的做法。
Thanks to Ben Alpert: https://groups.google.com/forum/#!topic/reactjs/8JgClU9jol0
感谢 Ben Alpert:https://groups.google.com/forum/#! topic/reactjs/ 8JgClU9jol0

