[英]react.js dynamically grabbing object resulting in undefined
I am learning react.js. 我正在学习react.js。 I have an object literal and I am trying to dynamically select an object within an object based upon what was chosen from a select input.
我有一个对象文字,我试图根据从选择输入中选择的内容动态选择对象内的对象。 I am getting undefined, however.
然而,我正在变得不确定。 I have tried both dot and bracket notation.
我试过点和括号表示法。 I am successfully grabbing the value of selected option and storing it within a variable.
我成功地获取了所选选项的值并将其存储在变量中。 Any ideas?
有任何想法吗?
Here is my object: 这是我的对象:
var horoList = {
aries: {
title: "JerkFace",
},
cancer: {
title: "Cancerous",
},
gemini : {
title: "GoofBall"
}
} ;
Here is some of my JSX within the render method: 这是我在render方法中的一些JSX:
<select name="pick-sign" onChange={this.handleChange}>
<option></option>
<option value="aries" >Aries</option>
<option value="cancer" >Cancer</option>
<option value="gemini" >Gemini</option>
<option value="taurus" >Taurus</option>
</select>
And here is my handle change method: 这是我的句柄更改方法:
handleChange: function(e) {
var selectedHoro = e.target.value;
console.log(selectedHoro); //outputs: aries
console.log(horoList); //outputs: Object {aries: Object, cancer: Object, gemini: Object}
console.log(horoList.aries); //ouputs: Object {title: "JerkFace"}
console.log(horoList['selectedHoro']); //outputs: undefined
// this.setState({
// horos: horoList.selectedHoro
// });
},
If you change this line: 如果您更改此行:
console.log(horoList['selectedHoro']); //outputs: undefined
To: 至:
console.log(horoList[selectedHoro]);
You should get the expected output. 你应该得到预期的输出。 When you use
horoList['selectedHoro']
, the literal string value selectedHoro
is used so it would be horoList.selectedHoro
. 当你使用
horoList['selectedHoro']
,使用了文字字符串值selectedHoro
,因此它将是horoList.selectedHoro
。 When you use horoList[selectedHoro]
, selectedHoro
is a variable and it's value is used to determine the property name you want to resolve so it would resolve to horoList.aeries
(when selectedHoro
=== aeries
). 当您使用
horoList[selectedHoro]
, selectedHoro
是一个变量,它的值用于确定您要解析的属性名称,因此它将解析为horoList.aeries
(当selectedHoro
=== aeries
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.