admin管理员组

文章数量:1331849

React documentation says

Don't worry about preputing values based on state — it's easier to ensure that your UI is consistent if you do all putation within render().

.html

This makes perfectly sense when the putations are small.

But I'm storing the bunch of large arrays in this.state for data visualizations I'm rendering on SVG. I have to pute several values based on those. The thing is that those putations are fairly heavy and it is impossible to pute those always within render.

So, how should I go about caching those putations while ensuring that I don't get inconsistent state with this.state and those puted variables?

React documentation says

Don't worry about preputing values based on state — it's easier to ensure that your UI is consistent if you do all putation within render().

http://facebook.github.io/react/docs/interactivity-and-dynamic-uis.html

This makes perfectly sense when the putations are small.

But I'm storing the bunch of large arrays in this.state for data visualizations I'm rendering on SVG. I have to pute several values based on those. The thing is that those putations are fairly heavy and it is impossible to pute those always within render.

So, how should I go about caching those putations while ensuring that I don't get inconsistent state with this.state and those puted variables?

Share Improve this question edited Mar 15, 2014 at 22:20 esamatti asked Mar 15, 2014 at 22:06 esamattiesamatti 19k11 gold badges81 silver badges83 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

I think I've figured it out.

I moved the large arrays to the state of the parent ponent and I'll just pass them as props to the visualization ponent. Then I just pute the values in ponentDidMount and ponentWillReceiveProps and save them into the state of the visualization ponent.

This avoids most of the useless puting in my case. But if it is not enough I can go further and diff the current props with the next props in ponentWillReceiveProps to determine if the putation is actually needed.

UPDATE: Now that I've worked more with React I think this should be done using memoizing. Reselect is good lib for that.

I tried some data visualization with React and SVG as well, and did not have any performance problem yet. React only rerender on state change, or parent ponent's state change so those putations are not run very often.

If in your case the ponents are updating frequently, you can try memoize the puting functions with lodash.

本文标签: javascriptIdiomatic way to cache computed values based on the state in ReactStack Overflow