Facebook React encourages您将可变 (state
) 和不可变 (props
) 状态分开:
Try to keep as many of your components as possible stateless. By doing this you'll isolate the state to its most logical place and minimize redundancy, making it easier to reason about your application.
当状态改变时,你应该调用setState
触发虚拟 DOM 差异,这将仅在需要时导致真正的 DOM 更新。
有一种方法可以通过调用 forceUpdate
手动触发 DOM 更新。但它是discouraged :
Normally you should try to avoid all uses of
forceUpdate()
and only read fromthis.props
andthis.state
inrender()
. This makes your application much simpler and more efficient.
但是,我见过的所有 React+Backbone 示例都忽略此建议,将模型和集合存储在 props
中并调用 forceUpdate
:
- http://www.thomasboyt.com/2013/12/17/using-reactjs-as-a-backbone-view.html
- https://github.com/usepropeller/react.backbone/blob/master/react.backbone.js
- https://gist.github.com/ssorallen/7883081
- http://eldar.djafarov.com/2013/11/reactjs-mixing-with-backbone/
甚至 React 自己的示例也使用了 forceUpdate
:
有没有更好的方法,它有什么好处?
最佳答案
Pete 的回答很棒。
Backbone 模型本质上是可变的,这(虽然本身不是问题)意味着在重新渲染时,您将无法与旧版本的模型进行比较。这使得通过定义 shouldComponentUpdate
进行智能优化变得更加困难。组件关键位置的方法。 (由于其他原因,您也无法轻松存储模型的旧版本,例如 implementing undo。)
调用 forceUpdate
只是跳过 shouldComponentUpdate
并强制组件重新呈现。请注意,调用 render
通常很便宜,如果 render
的输出发生变化,React 仍然只会接触 DOM,因此这里的性能问题并不常见。但是,如果您可以选择使用不可变数据(包括像 Pete 建议的那样从 toJSON()
传递原始模型属性对象),我强烈推荐它。
关于javascript - 将 React 与 Backbone 一起使用时,我可以避免使用 forceUpdate() 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21709905/