您好我最近刚开始学习反应原生。我现在正尝试使用以下代码从wordpress api获取数据,并使用这个确切的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>
)
}
}
任何建议将被认真考虑。
首先在括号中包含返回值
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}
在请求服务器时,Fetch将使用GET
方法作为默认值。要将其设置为制作POST
方法或其他方法,您需要在fetch中添加额外的参数在您的情况下,它将是
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需要标题和正文,请在使用之前确保检查API文档以便了解目的。
有关React native中的Fetch的更多信息,您可以访问它here有关什么是API的更多信息,您可以访问它here
希望这有帮助。