2017-02-23 1 views
1

내 App.jsx 파일이 아래에 있습니다.ReactJS- JSON 배열을 읽을 수 없습니다.

import React from 'react'; 
class App extends React.Component { 
constructor() { 
    super(); 

    this.state = { 
    data:require('json!./dataa.json') 

    } 
} 

render() { 
    return (
    <body> 
    <div> 
     <Header/> 
     <center> 
     <table> 
     <tr><th>NAME</th><th>VALUE</th><th>COLOR</th><th>Edit Table</th></tr> 
      <tbody> 
      {this.state.data.table.map(person, i) => <TableRow key = {i} data = {person} />)} 
      </tbody></table></center> 
    </div> 
    </body> 
); 
} 
} 

class Header extends React.Component { 
render() { 
    return (
    <div><center> 
     <h1>Creation of table from JSON</h1></center> 
    </div> 
); 
    } 
    } 

    class TableRow extends React.Component { 
    render() { 
    return (
    <tr> 
     <td>{this.props.data.NAME}</td> 
     <td>{this.props.data.VALUE}</td> 
     <td>{this.props.data.COLOR}</td> 
     <td contentEditable='true'></td> 
     </tr> 
     ); 
     } 
     } 

내보내기 기본 앱;

내 dataa.json 파일
[{"table": 
[{"NAME":"Alan","VALUE":12,"COLOR":"blue"}, 
{"NAME":"Shan","VALUE":13,"COLOR":"green"}, 
{"NAME":"John","VALUE":45,"COLOR":"orange"}, 
{"NAME":"Minna","VALUE":27,"COLOR":"teal"}] 
}] 

아래 질문과 같다 : 그것은 잘 컴파일됩니다. 하지만

주를 해결하기 위해 괜찮나 "지도 정의의 속성을 읽을 수 없습니다"브라우저에서 오류를 표시 :하지만 JSON 파일 등이,

[{"NAME":"Alan","VALUE":12,"COLOR":"blue"}, 
{"NAME":"Shan","VALUE":13,"COLOR":"green"}, 
{"NAME":"John","VALUE":45,"COLOR":"orange"}, 
{"NAME":"Minna","VALUE":27,"COLOR":"teal"}] 
}] 

답변

1

this.state.data 속성을 가지고 있지 않을 때 그것을 잘 작동합니다 table의 배열이기 때문에 단일 개체입니다.

{ 
    "table": [ 
    {"NAME":"Alan","VALUE":12,"COLOR":"blue"}, 
    {"NAME":"Shan","VALUE":13,"COLOR":"green"}, 
    {"NAME":"John","VALUE":45,"COLOR":"orange"}, 
    {"NAME":"Minna","VALUE":27,"COLOR":"teal"} 
    ] 
} 

-

올바른 JSON 구조와 this.state.data.table.map를 사용합니다.

+0

this.state.data.table.map이 제대로 작동하지 않습니다. ./app/components/dataa.json의 ERROR이 파일 유형을 처리하려면 적절한 로더가 필요할 수 있습니다. SyntaxError : 예기치 않은 토큰 (2 : 9) – James

관련 문제