简体   繁体   English

在 React 中,如何在循环中设置 state 变量?

[英]In React how can I set state variables in a loop?

I have a number of state variables (I am only showing 3):我有许多 state 变量(我只显示 3 个):

class IntroductionPage extends React.Component<SomePageProps, {inId: string,
  i1: string,
  i2: string
}> {
  constructor(props: any) {
    super(props);
    this.state = {inId:'',
      i1:'',
      i2:''
    };
  }

and I am reading key-value pairs from a DB:我正在从数据库中读取键值对:

+------------+------------+------------+
| start_type | field_name | start_text |
+------------+------------+------------+
| 0          | i1         | hi         |
+------------+------------+------------+
| 0          | i2         | it's me!   |
+------------+------------+------------+
| 0          | i3         | Schoon     |
+------------+------------+------------+


for (var key in response.data) {
  var dat = response.data[key];
  getStartType=dat['start_type']//JSON.stringify(dat['start_type']);
  for (var inner_key in dat) {
    console.log('key=' + inner_key + ' value=' + dat[inner_key]);
  }

gives

key=start_type value=0
key=field_name value=i1
key=start_text value=hi
...

Now is there any way I can loop through these retrieved value and set state, for example something like a loop or map version of this:现在有什么方法可以遍历这些检索到的值并设置 state,例如类似于循环或 map 版本:

this.setState({dat['field_name']:dat['start_text']});

so the first row returned would be fieldname= i1, start_text ='hi' and so the loop would setState ({i1:'hi'}) ?所以返回的第一行是 fieldname= i1, start_text ='hi' 所以循环会setState ({i1:'hi'})

React Docs:反应文档:

setState() does not immediately mutate this.state but creates a pending state transition. setState() 不会立即改变 this.state 而是创建一个挂起的 state 转换。 Accessing this.state after calling this method can potentially return the existing value.在调用此方法后访问 this.state 可能会返回现有值。 There is no guarantee of synchronous operation of calls to setState and calls may be >batched for performance gains无法保证对 setState 的调用的同步操作,并且调用可能 > 批处理以提高性能

don't call setState in a loop, just update a local variable inside aloop and then call the setSate method on that variable it will save you some rerenders不要在循环中调用 setState,只需在循环中更新局部变量,然后在该变量上调用 setSate 方法,它会为您节省一些重新渲染

As a technical question of "can I do this?"作为“我可以这样做吗?”的技术问题。 the answer is "Yes".答案是“是”。 It is ok to call setState inside a loop in your example because each state update is independent of each other and does not rely on previous values of the state.可以在示例中的循环内调用setState ,因为每个 state 更新彼此独立,并且不依赖于 state 的先前值。 React will likely batch the setState updates together so that you won't have multiple re-renders. React 可能会将setState更新批处理在一起,这样您就不会有多次重新渲染。

for (var key in response.data) {
  var dat = response.data[key];
  this.setState({ [dat.field_name]: dat.start_text });
}

You use brackets around [dat.field_name] because it is a variable property key.您在[dat.field_name]周围使用括号,因为它是一个变量属性键。 But variable property names are a problem for Typescript because it assumes that they are string instead of a valid key.但是变量属性名称对于 Typescript 来说是个问题,因为它假定它们是string而不是有效键。


I would probably do what @Sharon Geller suggests and call setState once with a combined value.我可能会按照@Sharon Geller 的建议做,并使用组合值调用setState一次。

const changes = response.data.reduce(
  (acc, curr) => ({ ...acc, [curr.field_name]: curr.start_text }),
  {}
);
this.setState(changes);

Technically this doesn't require an assertion because the type of changes is the empty object {} , but you might want to assert a type on the initial value {} as State .从技术上讲,这不需要断言,因为changes的类型是空的 object {} ,但您可能希望将初始值{} as State

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

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