簡體   English   中英

如何在React Native中使用`fetch()`函數從WordPress REST API檢索帖子?

[英]How do I use the `fetch()` function in React Native to retrieve posts from WordPress REST API?

我正在使用create-react-app構建一個React Native應用,該應用將顯示WordPress的列表帖子。 我從WordPress獲取數據時遇到問題。 我想我還沒有完全理解fetch()函數的工作方式。 這是我目前所擁有的:

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

在此先感謝您的幫助:)

我只能說Android:如果您正在運行仿真器,則localhost(127.0.0.1)將引用10.0.2.2將引用您的實際localhost。

因此,在這種情況下,您將使用以下命令: http://10.0.2.2:<port>/wordpress/wp-json/wp/v2/posts : http://10.0.2.2:<port>/wordpress/wp-json/wp/v2/posts :< http://10.0.2.2:<port>/wordpress/wp-json/wp/v2/posts

希望這可以幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM