Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
98 views
in Technique[技术] by (71.8m points)

javascript - Can I avoid forceUpdate() when using React with Backbone?

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?

question from:https://stackoverflow.com/questions/21709905/can-i-avoid-forceupdate-when-using-react-with-backbone

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...