0

我正在使用create-react-app構建一個React Native應用程序,該應用程序將顯示WordPress的列表帖子。我有一個從WordPress獲取數據的問題。我想我不完全瞭解fetch()函數的工作原理。 這是我的時刻:如何使用React Native中的`fetch()`函數從WordPress REST API檢索帖子?

export default class Posts extends Component { 
    constructor() { 
    super(); 
    this.state = { 
     posts: [] 
    } 
    } 
componentDidMount() { 
    let dataURL = "http://localhost/wordpress/wp-json/wp/v2/posts"; 
    fetch(dataURL) 
     .then(response => response.json()) 
     .then(response => { 
     this.setState({ 
      posts: response 
     }) 
     }) 
    } 
render() { 
    let posts = this.state.posts.map((post, index) => { 
     return 
     <View key={index}> 
     <Text>Title: {post.title.rendered}</Text> 
     </View> 
    }); 
return (
     <View> 
     <Text>List Of Posts</Text> 
     <Text>{posts}</Text> 
     </View> 
    ) 
    } 
} 

這是我得到的警告:在先進的

Possible Unhandled Promise Rejection (id:0) TypeError: Network request failed

感謝所有幫助:)

+1

嘗試 –

回答

3

我只能說對於Android: 如果您正在運行模擬器本地主機(127.0.0.1)將參考10.0.2.2將引用您的實際本地主機。

因此,在這種情況下,你可以使用這個: http://10.0.2.2:<port>/wordpress/wp-json/wp/v2/posts

希望這由你的主機IP替換本地主機有助於

相關問題