2017-02-20 239 views
0

使用React我想傳遞一個解析的JSON文件並映射到對象。但是看到它是一個對象,我可以如下使用Object.keys只映射對象:將對象映射到React中的子組件

const question = Object.keys(questions).map((data, index) => 
    <QuestionList questions={data} key={index} /> 

但是使用這個我只能訪問我的數據結構的頂層。所以使用這個代碼並傳遞我的對象。使用Object.keys()我只能訪問「問題」或「q1」或類型,文本,qId等。我無法一次傳遞所有對象屬性並指定我需要的子組件。

"questions": { 
    "q1": { 
     "qId": "1", 
     "type": "YN", 
     "text": "Text 1", 
     "tip": { 
     "logo": "assets/icons/gadgetz.svg", 
     "logofallback": "assets/img/gadgetz.png", 
     "heading": "Heading 1", 
     "text": "Text 2" 
     } 
    },... 

什麼是最簡單的方法來傳遞整個對象的子屬性,所以我可以在子組件中使用它們?我必須使用道具以外的東西嗎?

+0

爲什麼你不能傳遞整個對象? –

+0

是的,你可以傳遞一個對象作爲一個Prop類型。我認爲問題在於您傳遞的是圖片路徑的值,如果您使用的是webpack,這可能是一個問題。 – redconservatory

+0

也許錯誤是在別處看到,因爲你說這應該起作用。 究其原因,我認爲這是行不通的,因爲這樣的代碼: '{JSON.stringify(this.props.questions)}' 只返回鍵 「問題」, 「Q1,Q2,Q3」,或「qId,type,text」取決於我如何傳遞對象。 如果我寫'{JSON.stringify(this.props.questions.q1)}'​​對象是空的。 – dwigt

回答

1
const questionObjects = Object.values(JSON.stringify(theJSONinYourQuestion)); 

const questionComponents = questionObjects.map(question => <Question qId={question.qId} />); 

基本上,使用Object.values代替Object.keys,並且你已經有了一個可以使用的問題一個很好的陣列。

編輯:如果你沒有Object.values可不要在您的環境(it is experimental)

const originalQuestions = JSON.stringify(theJSONinYourQuestion); 
const questionKeys = Object.keys(orginalQuestions); 
const questionObjects = questionKeys.map(key => originalQuestions[key]); 
... 
1

您可以通過將其分配到該範圍之外的變量保持.MAP內訪問問題的對象。 Here's a jsBin顯示該想法

const objectOfQuestions = { 
    "questions": { 
     "q1": { 
      "qId": "1", 
      "type": "YN", 
      "text": "Text 1", 
      "tip": { 
       "logo": "assets/icons/gadgetz.svg", 
       "logofallback": "assets/img/gadgetz.png", 
       "heading": "Heading 1", 
       "text": "Text 2" 
      } 
     }, 
     "q2": { 
      "qId": "2", 
      "type": "YN", 
      "text": "Text 1", 
      "tip": { 
       "logo": "assets/icons/gadgetz.svg", 
       "logofallback": "assets/img/gadgetz.png", 
       "heading": "Heading 1", 
       "text": "Text 2" 
      } 
     } 
    } 
} 

const Question = ({ id, question }) => { 
    return (
    <div> 
     <h1>Question: {id}</h1> 
     <p>id: {question.qId}</p> 
     <p>type: {question.type}</p> 
     <p>text: {question.type}</p> 
    </div> 
) 
} 

const QuestionList = ({ questions }) => { 
    const questionObj = questions; 
    return (
    <div> 
     {Object.keys(questions.questions).map((key, i) => { 
     return (
      <div key={key}> 
      <Question id={key} question={questionObj.questions[key]} /> 
      </div> 
     ); 
     })} 
    </div> 
); 
} 

ReactDOM.render(<QuestionList questions={objectOfQuestions} />, document.getElementById('app'));