react:数组未定义

问题描述 投票:0回答:1

我有一个内部有对象的数组,看起来像这样

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:无法读取未定义的属性“块”

如何获得对此阵列的访问权限?

javascript arrays reactjs ecmascript-6 jsx
1个回答
0
投票

如果orchardSites(在你的jsx和你的onClick函数中)都是相同的,那么你想使用数组索引(i在jsx中)而不是orchardSite.code来访问数组。

这是因为OrchardSites [orchardSite.code]在某些情况下可能未定义,但OrchardSites [parseInt(i)]不会。

我建议你将'value'属性更改为“i”而不是orchardSite.code

© www.soinside.com 2019 - 2024. All rights reserved.