。谁能告诉我如何修复此错误错误错误类型错误:undefined不是对象(计算"userData. username")
我正在建立一个小应用程序,所以当你登录应用程序,进入主页比你需要允许权限,以获得您的城市名称的位置后,前端获得您的城市名称,然后它会发送您的城市名称到后端,以保存您的城市名称在数据库中,您的城市名称将保存在数据库"城市是一个字符串",直到这里一切正常,它保存到MongoDB数据库我的城市名称
现在,我在我的应用程序中有一个屏幕,所以我希望当用户进入该屏幕时,该用户将获得一个随机用户名和配置文件图片显示在前端注两个用户应该有相同的城市名称在数据库中的用户谁请求服务器应该有相同的城市作为其他一个随机用户在数据库中,我会两个相同的用户有相同的城市
主页:
import { StyleSheet, View, StatusBar } from 'react-native'
import React, { useEffect, useState } from 'react'
import Bottomnavbar from '../../Components/Bottomnavbar'
import TopNavbar from '../../Components/TopNavbar'
import FollowersRandomPost from '../../Components/FollowersRandomPost'
import AsyncStorage from '@react-native-async-storage/async-storage';
import * as Location from 'expo-location';
const Mainpage = ({ navigation }) => {
const [userdata, setUserdata] = useState(null);
const [location, setLocation] = useState(null);
const [errorMsg, setErrorMsg] = useState(null);
const [city, setCity] = useState(null);
useEffect(() => {
async function getUserData() {
try {
const userDataString = await AsyncStorage.getItem('user');
const userData = JSON.parse(userDataString);
setUserdata(userData);
} catch (err) {
alert(err);
}
}
getUserData();
}, []);
useEffect(() => {
async function getLocation() {
try {
let { status } = await Location.requestForegroundPermissionsAsync();
if (status !== 'granted') {
setErrorMsg('Permission to access location was denied');
}
let location = await Location.getCurrentPositionAsync({});
setLocation(location);
let city = await Location.reverseGeocodeAsync(location.coords);
setCity(city[0].city);
} catch (err) {
console.error(err);
}
}
getLocation();
}, []);
useEffect(() => {
async function sendCity() {
try {
const response = await fetch('http://10.0.2.2:3000/updateCity', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
city: city,
username: userdata.user.username
}),
});
const data = await response.json();
console.log('Success:', data);
} catch (err)
console.error('Error:', err);
}
}
if (userdata && city) {
sendCity();
}
}, [userdata, city]);
console.log(city)
return (
<View style={styles.container}>
<StatusBar />
<TopNavbar navigation={navigation} page={"MainPage"} />
<Bottomnavbar navigation={navigation} page={"MainPage"} />
<FollowersRandomPost />
</View>
);
}
export default Mainpage
更新城市的路线:
router.post('/updateCity', (req, res) => {
const city = req.body.city;
const username = req.body.username;
console.log(city)
console.log(`Updating city for user ${username} to ${city}`);
User.findOneAndUpdate({ username: username }, { city: city }, (err, user) => {
if (err) {
return res.status(500).json({
error: err
});
}
res.status(200).json({
message: 'City updated successfully'
});
});
});
我希望用户名和配置文件图片显示的屏幕:
import { StyleSheet, Text, View, Image } from 'react-native'
import React, { useState, useEffect } from 'react'
const SearchUserPage = () => {
return (
<View style={styles.container}>
<View style={styles.userSection}>
<View style={styles.imageContainer}>
<Image
style={styles.image}
source={profile pic here}
resizeMode="contain"
overflow="hidden"
/>
</View>
<Text style={styles.text}>User name here</Text>
</View>
</View>
)
}
export default SearchUserPage
获取一个具有相同城市的随机用户的后端代码:
router.get("/user", async (req, res) => {
try {
const city = req.body.city;
console.log(city);
const count = await User.countDocuments({ city: city });
if (count === 0) {
return res.status(404).json({ error: "No users found with that city" });
}
const randomUser = await User.aggregate([
{
$match: {
city: city,
},
},
{
$sample: {
size: 1,
},
},
{
$project: {
username: 1,
profilepic: 1, // Correct field name
},
},
]);
console.log(randomUser[0].username)
console.log(randomUser[0].profilepic)
res.json(randomUser);
} catch (err) {
console.log(err);
res.status(500).json({ error: err });
}
});
3条答案
按热度按时间gudnpqoy1#
ldioqlga2#
您可能还需要首先检查响应的状态,因为请求可能会失败,并显示404或500 HTTP错误,获取将实现承诺,但结果可能不是JSON,如下所示
如果你获取的数据来自一个对象数组,最好是初始化一个空数组,比如
dsekswqp3#
我想可能是因为你不接受json值,你能不能这样试试: