简体   繁体   中英

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

I'm using the create-react-app to build an React Native app that would show a list posts from WordPress. I have a problem fetching the data from WordPress. I think I'm not fully understanding how the fetch() function works. This is what I have at the moment:

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>
     )
  }
}

This is the warning that I get:

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

Thanks in advanced for any help :)

I can only speak for Android: If you are running the emulator localhost (127.0.0.1) will refer to that 10.0.2.2 will refer to your actual localhost.

So in that scenario you would use this: http://10.0.2.2:<port>/wordpress/wp-json/wp/v2/posts

Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM