2017-02-27 97 views
0

我有一個問題,我無法從WP API獲取的數據與愛可信反應JS 我的代碼:如何通過反饋js和axios從wordpress獲取API調用?

var React = require('react'); 
var ReactDOM = require('react-dom'); 
var axios = require('axios'); 

var Wordpress = React.createClass({ 
    getInitialState: function() { 
     return {posts: []}; 
    }, 
    componentDidMount() { 
     axios.get(`http://localhost/scareid/wp-json/wp/v2/posts`).then(res => { 
      const posts = res.data.map(obj => obj.data); 
      this.setState({posts}); 
     }); 
    }, 
    render() { 
     return (
      <div> 

       <h1>{`/r/${this.props.title}`}</h1> 
       <ul> 

        {this.state.posts.map(post => <li key={post.id}>{post.title}</li>)} 
       </ul> 
      </div> 
     ); 
    } 
}) 

module.exports = Wordpress; 

我的API

http://pastebin.com/9x4rgJmE

控制檯日誌數據: enter image description here

+0

即將該控制檯日誌? – paqash

+0

控制檯按圖像記錄數據 –

+0

jsx錯誤屏幕截圖http://imgh.us/Screen_Shot_2017-02-27_at_9.33.08_PM.png –

回答

0

好的發現它。

根本不需要map步驟,數組已經在res中返回。

替換:

const posts = res.data.map(obj => obj.data); 
      this.setState({posts}); 

有:

if (res && res.data) { 
this.setState({ 
    posts: res.data 
}); 
} 
+0

,但我有問題在返回 在這個錯誤{this.state.posts.map(posts =>

  • {post.title}
  • )} 但我console.log(this.state.posts.map(posts => posts.id));這樣的 輸出是ID職位 –

    +1

    感謝這是工作{this.state.posts.map(data =>

  • {data.title.rendered}
  • )} 感謝您的幫助,我很抱歉非常麻煩你 謝謝你的幫助 謝謝你的幫助,因爲我剛剛學會了一週的反應js –