我如何使用 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发言:
如果你是 运行 模拟器本地主机 (127.0.0.1) 将引用那个 10.0.2.2
将引用你的实际本地主机。
所以在那种情况下你会使用这个:
http://10.0.2.2:<port>/wordpress/wp-json/wp/v2/posts
希望对您有所帮助
我正在使用 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发言:
如果你是 运行 模拟器本地主机 (127.0.0.1) 将引用那个 10.0.2.2
将引用你的实际本地主机。
所以在那种情况下你会使用这个:
http://10.0.2.2:<port>/wordpress/wp-json/wp/v2/posts
希望对您有所帮助