2016-11-29 73 views
2

我是react.js的新手,我試圖在表中以JSON格式獲取服務器端數據。因此,我所做的是:使用axios.get呈現json數據

export default class TableUser extends React.Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
    table: [], 
    } 
} 
componentDidMount(){ 
    axios.get('http://www.reddit.com/r/reactjs.json') 
    .then((response)=>{ 
     const table = response.data.map(obj => obj.data); 
     this.setState({ table }); 
     }) 
    .catch((err)=>{ 

    }) 
} 

,我在一個<div>像這樣渲染:

render(){ 
    <div><p>{this.state.table.kind}</p></div> 
} 

爲什麼我沒收到kind價值? 請推薦!

回答

3

obj.data(在data有物業children這是Array)是ObjectArray,我覺得在這種情況下,更好地改變默認狀態,併爲kindString)一個領域,一個用於dataArray),像這樣

class TableUser extends React.Component { 
 
    constructor(props) { 
 
    super(props); 
 
    
 
    this.state = { 
 
     kind: '', 
 
     data: [] 
 
    }; 
 
    } 
 
    
 
    componentDidMount(){ 
 
    axios 
 
     .get('https://www.reddit.com/r/reactjs.json') 
 
     .then(({ data })=> { 
 
     \t this.setState({ 
 
      kind: data.kind, 
 
      data: data.data.children 
 
     }); 
 
     }) 
 
     .catch((err)=> {}) 
 
    } 
 
     
 
    render() { 
 
    const child = this.state.data.map((el, index) => { 
 
     return <div key={index}> 
 
     <p>Title - { el.data.title }</p> 
 
     <p>Author - { el.data.author }</p> 
 
     </div> 
 
    }); 
 

 
    return <div> 
 
     <p>{ this.state.kind }</p> 
 
     <div>{ child }</div> 
 
    </div>; 
 
    } 
 
} 
 

 
ReactDOM.render(
 
    <TableUser />, 
 
    document.getElementById('container') 
 
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.15.3/axios.js"></script> 
 
<div id="container"></div>

+1

由於它的作品! :) – NDeveloper