简体   繁体   English

React 为复杂处理存储数据

[英]React Storing data for complicated processing

I am somewhat new to ReactJS.我对 ReactJS 有点陌生。

I want to store data for complicated computations in ReactJS.我想在 ReactJS 中存储用于复杂计算的数据。 Since the setState is asynchronous, I cannot be bothered to store all the required data inside state as it would be next to impossible to do what I want.由于setState是异步的,我无法将所有必需的数据存储在state因为几乎不可能做我想做的事情。

I was thinking of doing the following: store the needed variables inside an object inside the state itself.我正在考虑执行以下操作:将所需的变量存储在状态本身内的对象中。 Eg the state defined in the constructor is the following object例如在构造函数中定义的状态是以下对象

constructor(props){
    this.state = { complicated_storage: { x : 123, y : 324 } }
}

This way I can manipulate this.state.compicated_storage.x or this.state.compicated_storage.y , and do stuff like this.state.compicated_storage.x = 4 without worrying about asynchronous behavior.通过这种方式,我可以操作this.state.compicated_storage.xthis.state.compicated_storage.y ,并执行诸如this.state.compicated_storage.x = 4类的操作,而无需担心异步行为。

Is this a bad way of doing stuff in ReactJS.这是在 ReactJS 中做事的糟糕方式吗? I noticed that with this you can bypass the entire setState mechanism, and just store all my variables inside the object within the state .我注意到通过这个你可以绕过整个setState机制,只需将我所有的变量存储在state的对象中。

Thank You谢谢你

Is this a bad way of doing stuff in ReactJS.这是在 ReactJS 中做事的糟糕方式吗? I noticed that with this you can bypass the entire setState mechanism, and just store all my variables inside the object within the state.我注意到通过这个你可以绕过整个 setState 机制,只需将我的所有变量存储在状态内的对象中。

The entire purpose of state is re-rendering components whenever it changes. state 的全部目的是在组件发生变化时重新渲染它。 If you modify it directly, such as state.someVariable = 2 , React will not know about your change, and it will not rerender your components after the change (however, the change will be reflected if something else later causes a rerender).如果你直接修改它,比如state.someVariable = 2 ,React 不会知道你的更改,并且它不会在更改后重新渲染你的组件(但是,如果其他东西导致了重新渲染,更改将被反映)。

If you need a change to some data trigger a rerender and update the view, use state together with setState .如果您需要更改某些数据触发重新渲染并更新视图,请将 state 与setState一起使用。

If not, you can simply use a class field, rather than store it inside state.如果没有,您可以简单地使用类字段,而不是将其存储在状态中。

Besides, I'm not sure in what way asynchrony you think will impede your goals, so perhaps you should be clearer there.此外,我不确定您认为异步会以何种方式阻碍您的目标,所以也许您应该在那里更清楚。 State being asynchronous just means that changes to state are made "a little later" after the function is called (it's a whole other topic), so React can batch updates for performance reasons.异步状态仅意味着在调用函数后“稍后”对状态进行更改(这是另一个主题),因此出于性能原因,React 可以批量更新。

Last but not least, you should look into hooks (useState), instead of using class components.最后但并非最不重要的一点是,您应该查看钩子 (useState),而不是使用类组件。

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

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