简体   繁体   English

使用变量值从 React 类的状态问题中检索对象值

[英]Using variable value to retrieve object value from the React class' state issue

I have a state that appears like so:我有一个看起来像这样的状态:

this.state = {
  dag: {
       topField: '',
       leftField: '',
       centreField: '',
       rightField: '',
       bottomField: ''
   },

   currentNode: ''
}

The currentNode in my program gets updates with one of the five variable names which are in the dag object eg currentNode = 'rightField'.我的程序中的 currentNode 使用 dag 对象中的五个变量名称之一进行更新,例如 currentNode = 'rightField'。

In my program, I am trying to access the part of the dag which has the value stored in currentNode:在我的程序中,我试图访问存储在 currentNode 中的值的 dag 部分:

For instance, imagine currentNode = 'rightField' and that I am trying to log the rightField part of the dag object.例如,想象 currentNode = 'rightField' 并且我正在尝试记录 dag 对象的 rightField 部分。 Since I have found on other answers on StackOverflow, that to access the value of a variable it is common practice to write 'this[variable]' I have been trying this :由于我在 StackOverflow 上的其他答案中发现,为了访问变量的值,通常的做法是编写“this[variable]”,我一直在尝试这样做:

console.log(this.state.dag.this[currentNode]);

But I get errors for this which state that there is no 'rightField' of undefined.但是我收到错误,指出没有未定义的“rightField”。 Yet I am still able to print the value using the explicit variable name ie console.log(this.state.dag.rightField);但是我仍然可以使用显式变量名称打印值,即console.log(this.state.dag.rightField); instead of console.log(this.state.dag.this[currentNode]);而不是console.log(this.state.dag.this[currentNode]);

埃罗斯

Why is this and how do I actually use the variable holding the variable name (currentNode holding the position of right, left, top, etc) to get the correct part of the dag (right, left, top, etc)?为什么会这样,我如何实际使用保存变量名称的变量(保存右、左、上等位置的 currentNode)来获取 dag 的正确部分(右、左、上等)?

this.state.dag.this[currentNode] <- Wrong. this.state.dag.this[currentNode] <- 错误。

dag doesn't have 'this' as a property. dag 没有“this”作为属性。 You are considering this operator wrongly.您错误地考虑了this运算符。 You should learn more about it.你应该更多地了解它。

this.state.dag[currentNode] <- Right this.state.dag[currentNode] <- 右

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors

As Robin mentioned in comment, make sure currentNode variable exists and it refers to this.state.currentNode正如 Robin 在评论中提到的,确保currentNode变量存在并且它指的是this.state.currentNode

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

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