简体   繁体   English

使用react.js强制重新渲染(更新状态并更新DOM)

[英]Force a re-render (update the state and update the DOM) immediately with react.js

I realize that calling setState does not update this.state immediately, nor does it immediately call render and refresh the DOM. 我意识到调用setState不会立即更新this.state ,也不会立即调用render并刷新DOM。 The docs say 文档说

setState() does not immediately mutate this.state but creates a pending state transition. setState()不会立即改变this.state,但会创建挂起状态转换。 Accessing this.state after calling this method can potentially return the existing value. 调用此方法后访问this.state可能会返回现有值。

There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains. 无法保证对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? 有办法吗?

You can use forceUpdate for 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(). 如果你的render()方法从this.props或this.state以外的东西读取,你需要通过调用forceUpdate()来告诉React何时需要重新运行render()。 You'll also need to call forceUpdate() if you mutate this.state directly. 如果你直接改变this.state,你还需要调用forceUpdate()。

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

You can use a forceUpdate in conjunction with having a key on the top level component as so.. 您可以将forceUpdate与顶级组件上的密钥结合使用。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM