我有一个数组,里面的对象看起来像这样
OrchardSite > Array(16) > 0: {blocks: Array (3), name: "asdasd", code: "R101A"}
1: {blocks: Array (7), name: "dasdas", code: "R555"}
我有看起来像这样的JSX
<select className="input-field-slider dropdown w-select" onChange={() => this.setOrchard}>
<option>All Sites</option>
{orchardSites
.map((orchardSite, i) => (
<option key={i} value={orchardSite.code}>
{orchardSite.code + " " + orchardSite.name}
</option>
))}
每次用户从下拉菜单中选择一个选项时,我都会触发此功能。
setOrchard = (event) => {
const orchardId = event.target.value;
console.log("orchardID", orchardId) // returns selected ID
console.log("OrchardSite", this.props.metadata.OrchardSites) // returns array
console.log("testing1", this.props.metadata.OrchardSites[parseInt("R1018A")] // undefined
console.log("testing2", this.props.metadata.OrchardSites[parseInt(orchardId)]) // undefined
console.log("new value", this.props.metadata.OrchardSites[parseInt(orchardId)].blocks) // Cannot read property 'blocks' of undefined
if (orchardId.length > 0) {
if (!this.props.metadata.OrchardSites[parseInt(orchardId)].blocks)
this.props.metadata.orchardSites[parseInt(orchardId)].blocks = []
console.log("SetttingOrchardLocation", this.props.metadata.orchardSites)
this.setState({ orchardId: orchardId, block: null, area: null, row: null, site: Object.assign({}, this.props.metadata.orchardSites[parseInt(orchardId)]) })
console.log("Testing OrchardId", this.props.metadata.orchardSites[parseInt(orchardId)])
// parseInt to get access to the array index, (Maybe I need to .ToString() somewhere?
}
}
哪个回来。
未捕获的TypeError:无法读取未定义的属性“块”
我如何获得对该阵列的访问权限?
答案 0 :(得分:0)
如果两个orchardSites(在您的jsx和onClick函数中)都相同,则您要使用数组索引(在jsx中为i)而不是orchardSite.code来访问该数组。
这是因为在某些情况下OrchardSites [orchardSite.code]可能是不确定的,而OrchardSites [parseInt(i)]则不能。
我建议您将“值”属性更改为“ i”,而不是orchardSite.code