2017-07-20 22 views
0

我在從包含JSON的對象設置變量時遇到問題。這裏是返回的JSON看起來像使用密鑰從回調函數返回值

{ 
    "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" 
    } 
    ] 
} 

在我的React代碼中,我基本上在不同的組件中使用JSON的不同部分。所以我的應用程序組件將狀態交給各自的組件(概述和Meds)。概述工作正常可能是因爲我把整個狀態下移,然後根據鍵可以獲得根值(即FName,LName)。不過,我正在努力應對Meds做什麼。我正在嘗試從狀態下將JSON的藥物部分向下傳遞,以便「藥物」窗格可以顯示傳遞給它的內容。

class App extends ReactComponent { 
    .... 
    render() { 
    //what worked before was needing to set state to this.state.PATIENT[0].Meds 
    //use console.log{this.state.PATIENT} to see if things output properly 
    return (
     <App> 
     <Article> 
      <Header> 
      <Section> 
       <Accordion openMulti={false} active='0'> 
       <AccordionPanel heading='Overview'> 
        <Box colorIndex='light-2' full='horizontal' direction='row' flex={false}> 
        <OverviewPane overview={this.state.PATIENT}/> 
        </Box> 
       </AccordionPanel> 
       <AccordionPanel heading='Medications'> 
        <Box colorIndex='light-2' full='horizontal' direction='row' flex={false}> 
        **<MedicationsPane meds={this.state.PATIENT.map(function (P,)){return P.Meds})}/>** 
       </AccordionPanel> 
       </Accordion> 
      </Section> 
      </Header> 
     </Article> 
     </App> 
    ); 
    } 
} 


class MedicationsPane extends React.Component { 

    constructor(props) { 
    super(props); 
    autoBind(this); 
    } 

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

我想我需要傳遞像P.id這樣的密鑰才能返回Meds,但似乎無法通過索引。或者我需要使用Children.Map?真的困惑在這一點上,任何幫助,將不勝感激。

+0

我真的不知道你的問題。你的MedicationsPane需要一系列的Meds(我不明白你爲什麼映射病人,因爲它是一個對象而不是數組),並且你不知道如何正確渲染它,因爲你不知道應該放什麼「關鍵「?你能用(簡化的)MedicationsPane組件編輯你的代碼並顯示你確切的問題嗎? – Nevosis

+0

Nevosis MedicationsPane似乎工作正常,當我硬編碼我的JSON。我認爲問題出現在我的概覽窗格中,並將狀態交給meds變量。當我嘗試一些簡單的工作,如meds = {this.state.PATIENT.Meds [0]},我得到一個未定義的錯誤。我 – jgoraya

+0

請做一個小提琴。如果你發送PATIENT.Meds [0],你不能映射道具,因爲它的一個對象(沒有meds節點,這就是它未定義的原因)。我認爲你在使用地圖時遇到問題 – Nevosis

回答

0

您在json中的Med是一個只有一個對象的數組,因此訪問Meds使用它就像json.Meds [0]。像這樣傳遞:

<MedicationsPane meds={this.state.PATIENT.Meds[0]}/> 
+0

感謝法瓦茲。我最初嘗試了這一點,但當我做了一個錯誤返回,說明「未捕獲TypeError:無法讀取未定義的屬性'0' – jgoraya

+0

@ kuruption213做一個'console.log(this.state)'並查看json是否存在。也許你也可以分享迴應。看起來患者的格式與上面給出的格式不同。 – Fawaz