将 React 与 Backbone 一起使用时,我可以避免 forceUpdate() 吗? [英] Can I avoid forceUpdate() when using React with Backbone?

查看:19
本文介绍了将 React 与 Backbone 一起使用时,我可以避免 forceUpdate() 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Facebook React 鼓励你分离可变(state)和不可变(props)状态:

<块引用>

尽量让你的组件保持无状态.通过这样做,您可以将状态隔离到最合乎逻辑的位置,并最大限度地减少冗余,从而更轻松地推理您的应用程序.

当状态改变时,你应该调用setState 触发虚拟 DOM 差异,仅在需要时才会导致真正的 DOM 更新.

有一种方法可以通过调用 <手动触发 DOM 更新code>forceUpdate 但它是不鼓励::><块引用>

通常你应该尽量避免使用 forceUpdate() 并且只读取 this.propsthis.staterender() 中.这使您的应用程序更简单、更高效.

然而,我所见过的所有 React+Backbone 示例忽略这个建议并将模型和集合存储在 props 中并调用 forceUpdate:

即使是 React 自己的例子也使用 forceUpdate:

有没有更好的方法,它会带来什么好处?

解决方案

Pete 的回答很棒.

Backbone 模型本质上是可变的,这(虽然本身不​​是问题)意味着在重新渲染时,您将无法与旧版本的模型进行比较.这使得通过定义 shouldComponentUpdate<进行智能优化变得更加困难/code> 组件关键位置的方法.(由于其他原因,例如 实现撤销.)

调用 forceUpdate 只会跳过 shouldComponentUpdate 并强制组件重新渲染.请注意,调用 render 通常很便宜,如果 render 的输出发生变化,React 仍然只会接触 DOM,因此这里的性能问题并不常见.但是,如果您可以选择使用不可变数据(包括按照 Pete 的建议从 toJSON() 传递原始模型属性对象),我强烈推荐它.

Facebook React encourages you to separate mutable (state) and immutable (props) state:

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.

When the state changes, you are supposed to call setState to trigger virtual DOM diff, which will cause a real DOM update only when this is needed.

There is a way to trigger DOM update manually by calling forceUpdate but it is discouraged:

Normally you should try to avoid all uses of forceUpdate() and only read from this.props and this.state in render(). This makes your application much simpler and more efficient.

However, all React+Backbone examples I have seen ignore this advice and store models and collections in props and call forceUpdate:

Even React's own example uses forceUpdate:

Is there a better way, though, and what benefits would it give?

解决方案

Pete's answer is great.

Backbone models are inherently mutative, which (while not a problem in itself) means that when rerendering, you won't have the old version of the model to compare to. This makes it harder to do intelligent optimizations by defining shouldComponentUpdate methods in key places on your components. (You also lose out on the ability to easily store old versions of your model for other reasons, like implementing undo.)

Calling forceUpdate merely skips shouldComponentUpdate and forces the component to rerender. Note that calling render is usually cheap, and React will still only touch the DOM if the output of render has changed, so performance problems here aren't common. However, if you have the choice to use immutable data (including passing around raw model property objects from toJSON() as Pete suggests), I'd highly recommend it.

这篇关于将 React 与 Backbone 一起使用时,我可以避免 forceUpdate() 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆