enter image description here尝试使用fetch-api在react-native中显示博客内容。我对语法感到非常困惑,因为随着我上网的相关示例变得越来越复杂。该API是从PHP-PDO / MySQL本地生成的,我在POSTMAN上测试了一个URL。但是,每次尝试使用fetch-api和console.log()显示内容时,都会收到错误消息。
我试图在线检查类似的问题,但由于问题与我的不同,因此似乎模棱两可。当时我以为是因为我在渲染器中使用了map(),所以我改成了FlatList。
错误:
This error is located at:
in VirtualizedList (at FlatList.js:625)
in FlatList (at Category.js:32)
in RCTView (at View.js:45)
in View (at Category.js:31)
in Category (at App.js:10)
in RCTView (at View.js:45)
in View (at App.js:9)
in App (at renderApplication.js:34)
in RCTView (at View.js:45)
in View (at AppContainer.js:98)
in RCTView (at View.js:45)
in View (at AppContainer.js:115)
in AppContainer (at renderApplication.js:33)
import React, { Component } from 'react';
import
{ Text,
View,
FlatList,
StyleSheet
} from 'react-native';
export default class Category extends Component {
constructor(props){
super(props);
this.state = {
data: []
}
}
componentWillMount() {
const that = this;
fetchData = async () => {
const response = await fetch("http://localhost/rest_api_myblog/api/post/read.php");
const json = await response.json();
that.setState({ data: json});
console.log(json);
}
}
render() {
return(
<View style={styles.container}>
<FlatList
data={this.state.data}
keyExtractor={(x, i) => i}
renderItem={({ item }) =>
<Text>
{`${item.author} ${item.category_name}`}
</Text>}
/>
</View>
);
}
}
我要显示帖子内容
答案 0 :(得分:1)
我遇到了同样的错误,因为我试图执行对象而不是数组。确保您正在使用FlatList数组
答案 1 :(得分:0)
我已经使用axios调整了您的代码。尝试看看您是否使用axios,但需要使用apmios将axios添加到项目中axios --save或yarn添加axios,然后可以将其导入。 所做的事情将为您提供有关如何获得结果的线索。
import React, { Component } from 'react';
import {
ScrollView,
StyleSheet,
View,
Text
} from 'react-native';
import axios from 'axios';
export default class Post extends Component{
constructor(props){
super(props);
this.state = {
posts: []
}
}
componentDidMount(){
axios.get(`http://localhost/rest_api_myblog/api/post/read.php`) //I used backtick
//.then(json => console.log(json.data.data[0].id)) //try to traverse to your json element by doing console.log to ensure you have a feedback
.then(json => json.data.data.map(mydata =>(
{
author: `${mydata.author} ${mydata.id}`,
id: mydata.registered
}
)))
//.then(newData => console.log(newData)) //also I did a console.log to check if the newData is working.
.then(newData => this.setState({posts: newData}))
.catch(error => alert(error))
}
render(){
return (
<ScrollView>
{
this.state.posts.map((post, index) =>(
<Text key={index}>
{post.author}
</Text>
))
}
</ScrollView>);
}
}
我希望这对您有帮助