我正在尝试从数据库中获取所有文本(像帖子一样发推).反应原生



我正在尝试从数据库中获取所有文本(像帖子一样发推(,但它显示错误类型错误:未定义不是一个函数(靠近'...帖子.地图...'(

下面是我的代码:

import React, {useEffect, useState} from 'react';
import {ActivityIndicator, Text, View, FlatList} from 'react-native';
import stylesheet from '../src/styles/HomeStyle';
import AsyncStorage from '@react-native-community/async-storage';
function FeedScreen() {
// const [posts, setPosts] = useState('loading');
const [posts, setPosts] = useState({
text: '',
id: '',
});
const Boiler = async () => {
const token = await AsyncStorage.getItem('token');
fetch('http://192.168.1.5:3000/post', {
headers: new Headers({
Authorization: 'Bearer ' + token,
}),
})
.then(res => res.json())
.then(res => {
setPosts(res.posts);
})
.catch(err => console.log(err));
};
useEffect(() => {
Boiler();
}, []);
return (
<View style={stylesheet.container}>
{posts.map(post => (
<Text key={post.id}>{post.text}</Text>
))}
</View>
);
}
export default FeedScreen;

问题是帖子的初始值是一个帖子,而不是一个帖子数组。我还重命名了Boiler,因为初始大写应该保留给组件或类,并将其移动到useEffect内:

const FeedScreen = () => {
const [posts, setPosts] = useState([]); // Here was the issue
useEffect(() => {
const boiler = async () => {
const token = await AsyncStorage.getItem("token");
fetch("http://192.168.1.5:3000/post", {
headers: new Headers({
Authorization: "Bearer " + token
})
})
.then(res => res.json())
.then(res => {
setPosts(res.posts);
})
.catch(err => console.log(err));
};
boiler();
}, []);
return (
<View style={stylesheet.container}>
{posts.map(post => (
<Text key={post.id}>{post.text}</Text>
))}
</View>
);
};
export default FeedScreen;

相关内容

  • 没有找到相关文章

最新更新