代码之家  ›  专栏  ›  技术社区  ›  jgoraya

在React中将变量设置为子节点

  •  0
  • jgoraya  · 技术社区  · 9 年前

    {
      "id": "6",
      "FName": "Chris",
      "LName": "Baker",
      "Height": "6'2",
      "Meds": [
        {
          "MedicationName": "acetaminophen",
          "Doseage": "Take 2 daily with food",
          "NumRefills": 2,
          "RefillExp": "2017-05-31T15:38:50.02Z",
          "FirstPrescribed": "2017-05-31T15:38:50.02Z",
          "WFID": "string"
        }
      ]
    }
    

    我能够在父级设置变量,例如。。。。

    class App extends ReactComponent {
      ....
      render() {
        return (
        ....
        <OverviewPane overview={this.state.PATIENT}/>
         ....
        );
       }
    }
    

    然后在Overview窗格中,我可以根据JSON中的数据按预期设置字段。(见下文)

    class OverviewPane extends ReactComponent {
          ....
          render() {
            return (
            ....
            <td>{this.props.overview.map(function(P){return <label key={P.id}> First Name: {P.FName}</td>
             ....
            );
           }
        }
    

    然而,我无法获得药物,所以我尝试了以下几点。。。

    class App extends ReactComponent {
      ....
      render() {
        return (
        ....
        <MedicationsPane meds={this.state.PATIENT.Meds[0]}/>
         ....
        );
       }
    }
    

    在药物窗格中。。。

    class MedicationsPane extends React.Component {  
    ...
      render () {
        return (
          <List>
                {this.props.meds.map(function(Meds) {
                return <ListItem justify='between' separator='horizontal' key={Meds.MedicationName}>{Meds.MedicationName}</ListItem>;
              })}
          </List>
        );
      }
    }
    

    2 回复  |  直到 9 年前
        1
  •  1
  •   Venugopal    9 年前

    我收到错误“无法读取未定义的属性“0”。

    OverviewPane 组件表明 this.state.PATIENT 作为一个数组,所以访问 Meds 像 this.state.PATIENT.Meds 将导致 undefined 药物 上的属性 PATIENT 数组)和错误。

    class App extends ReactComponent {
      ....
      render() {
        return (
        ....
        {this.state.PATIENT.map(p => {
          return (p.Meds && p.Meds.length > 0) ? <MedicationsPane meds={p.Meds}/> : null;
        })}
         ....
        );
       }
    }
    

    其次,您正在将药物详细信息发送给 MedicationsPane 像 overview this.props.meds .将它们更改为相同的名称。

        2
  •  1
  •   marzelin    9 年前

    你正在通过 this.state.PATIENT 到 OverviewPane 像 overview

    在里面 概述窗格 this.state.PATIENT 是一个数组。

    MedicationsPane 你在治疗 this.state.PATIENT Meds 所有物如果 this.state.PATIENT 是一个数组,您应该访问 药物 属性为 this.state.PATIENT[PATIENTINDEX].Meds[0]