2017-03-21 44 views
1

我已經導入axios庫和React。我在React分量上做get調用,請求是正確的,也返回響應,它給了我這樣的:GET請求在React Component中不起作用

{"functionality": [ 
     {"category": "", "price": 2.0, "moltiplicator": 100.0, "name": "Plat"} 
    ] 
} 

但是當我設置響應狀態變量,它不工作,這是代碼:

export class FetchDemo extends React.Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
     posts: [] 
    }; 
    } 

    componentDidMount() { 
    axios.get(`http://127.0.0.1:8080/get_platforms`) 
     .then(res => { 
     this.setState({ 
      posts: res.functionality 
      }); 
     }); 
    } 

    render() { 
    return (
     <div> 
     <ul> 
      {this.state.posts.map(post => 
      <li >{post.category}</li> 
     )} 
     </ul> 
     </div> 
    ); 
    } 
} 
+0

來自'axios.get('http://127.0.0.1:8080/get_platforms')'的響應是JSON字符串還是JS對象? –

+0

你確定關於console.llog(res.functionality)? 請將res放置在payphesis axios.get('http://127.0.0.1:8080/get_platforms').then((res)=> {...} – alireza

+0

是一個json字符串 –

回答

2

問題就出在你的響應的處理,你應該使用res.data,不僅res

export class FetchDemo extends React.Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
     posts: [] 
    }; 
    } 

    componentDidMount() { 
    axios.get(`http://127.0.0.1:8080/get_platforms`) 
     .then(res => { 
     this.setState({ 
      posts: res.data.functionality 
      }); 
     }); 
    } 

    render() { 
    return (
     <div> 
     <ul> 
      {this.state.posts.map(post => 
      <li >{post.category}</li> 
     )} 
     </ul> 
     </div> 
    ); 
    } 
} 

UP DATE:請參閱axios示例:https://github.com/mzabriskie/axios/blob/master/examples/get/index.html