React Native 我如何修复此错误错误类型错误:undefined不是对象(计算“userData. username”)

myzjeezk  于 2023-01-09  发布在  React
关注(0)|答案(3)|浏览(420)

。谁能告诉我如何修复此错误错误错误类型错误: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 });
    }
  });
gudnpqoy

gudnpqoy1#

import { StyleSheet, Text, View, Image } from 'react-native'
import React, { useState, useEffect } from 'react'

const SearchUserPage = () => {
  const [userData, setUserData] = useState();

  useEffect(() => {
    async function fetchUser() {
      try {
        const response = await fetch('http://10.0.2.2:3000/user');
        const data = response.json();
        setUserData(data);
      } catch (error) {
        console.error(error);
      }
    }

    fetchUser();
  }, []);

  // return null while waiting tor userData to load
  // you can return a spinner or "loading" text instead
  if (!userData) return null;
  
  return (
    <View style={styles.container}>
      <View style={styles.userSection}>
        <View style={styles.imageContainer}>
          <Image
            style={styles.image}
            source={{ uri: userData.profilepic }}
            resizeMode="contain"
            overflow="hidden"
          />
        </View>
        <Text style={styles.text}>{userData.username}</Text>
      </View>
    </View>
  )
}

export default SearchUserPage
ldioqlga

ldioqlga2#

您可能还需要首先检查响应的状态,因为请求可能会失败,并显示404或500 HTTP错误,获取将实现承诺,但结果可能不是JSON,如下所示

useEffect(() => {
    async function fetchUser() {
      try {
        const response = await fetch('http://10.0.2.2:3000/user');
        if(response.ok) {
            const data = await response.json();
            setUserData(data); // or data.data i don't know the structure from your api
        }
      } catch (error) {
        console.error(error);
      }
    }
    fetchUser();
  }, []);

如果你获取的数据来自一个对象数组,最好是初始化一个空数组,比如

const [userData, setUserData] = useState([]);
dsekswqp

dsekswqp3#

我想可能是因为你不接受json值,你能不能这样试试:

import { StyleSheet, Text, View, Image } from 'react-native'
import React, { useState, useEffect } from 'react'

const SearchUserPage = () => {
  const [userData, setUserData] = useState();

  useEffect(() => {
      async function fetchUser() {
        fetch('http://10.0.2.2:3000/user', {
          method: 'GET',
          headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
          }
          body: JSON.stringify({city: 'London'}),
        }).then(response => {
          setUserData(response.json());
          return response.json();
        });
      }

      fetchUser();
    }, []);

  return (
    <View style={styles.container}>
      <View style={styles.userSection}>
        <View style={styles.imageContainer}>
          <Image
            style={styles.image}
            source={{ uri: userData.profilepic }}
            resizeMode="contain"
            overflow="hidden"
          />
        </View>
        <Text style={styles.text}>{userData.username}</Text>
      </View>
    </View>
  )
}

export default SearchUserPage

相关问题