反应本机 Wordpress API 不获取帖子

React native Wordpress API not fetching posts

你好,我最近才开始学习 React Native。 我现在正在尝试使用以下代码和这个确切的 api 地址从 wordpress api 获取数据,但没有加载任何内容。

    import React from 'react';
    import { FlatList, ActivityIndicator, Text, View  } from 'react-native';

    export default class FetchExample extends React.Component {

    constructor() {
    super();
    this.state = {
      posts: []
    }
    }
    componentDidMount() {
    let dataURL = "https://click9ja.com/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>
     )
  }
}

如有任何建议,我们将不胜感激。

Fetch 向服务器请求时默认使用 GET 方法。要将其设置为创建 POST 方法或其他方法,您需要在获取中添加额外的参数 在你的情况下它将是

fetch('https://click9ja.com/wp-json/wp/v2/posts', {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    firstParam: 'yourValue',
    secondParam: 'yourOtherValue',
  }),
});

部分 API 需要 headers 和 body,请务必在使用前查看 API 文档以便理解。

有关 React native 中 Fetch 的更多信息,您可以访问它 here 有关什么是 API 的更多信息,您可以访问它 here

希望对您有所帮助。

首先将 return 值括在括号

let posts = this.state.posts.map((post, index) => {
      return (
      <View key={index}>
      <Text>Title: {post.title.rendered}</Text>
      </View> 
     );
    });

其次,您不能在文本标记中呈现变量。应该是这样的

<View>{varaible}</View>

因此,<Text>{posts}</Text> 应该只是 {post}