如何修复这个错误?错误类型:空对象不是对象(评估’userdata.user’)。

huangapple go评论81阅读模式
英文:

How can i fix this error? ERROR TypeError: null is not an object (evaluating 'userdata.user')

问题

以下是翻译好的部分:

import { StyleSheet, Text, View, StatusBar } from 'react-native'
import React, { useEffect, useState } from 'react'
import { containerFull } from '../../CommonCss/pagecss'
import { formHead } from '../../CommonCss/formcss'
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] = React.useState(null)
    const [location, setLocation] = useState(null)
    const [errorMsg, setErrorMsg] = useState(null)
    const [city, setCity] = useState(null)
    const [data, setData] = useState(null)

    useEffect(() => {
        AsyncStorage.getItem('user')
            .then(data => {
                // console.log('async userdata ', data)
                setUserdata(JSON.parse(data))
            })
            .catch(err => alert(err))
    }, [])

    console.log('userdata ', userdata)

    useEffect(() => {
        (async () => {
            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)
        })()
    }, [])

    const sendCity = () => {
        setCity(city)
        fetch('http://192.168.1.52:3000/updateCity', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                city: city,
                username: userdata.user.username
            }),
        })
            .then((response) => response.json())
            .then((data) => {
                console.log('Success:', data)
            })
            .catch((error) => {
                console.error('Error:', error)
            })
    }

    useEffect(() => {
        sendCity()
    }, [])

    return (
        <View style={styles.container}>
            <StatusBar />
            <TopNavbar navigation={navigation} page={"MainPage"} />
            <Bottomnavbar navigation={navigation} page={"MainPage"} />
            <FollowersRandomPost />
        </View>
    )
}

export default Mainpage

const styles = StyleSheet.create({
    container: {
        width: '100%',
        height: '100%',
        backgroundColor: 'black',
        paddingVertical: 50,
    }
})
import { StyleSheet, Text, View, StatusBar } from 'react-native'
import React, { useEffect, useState } from 'react'
import { containerFull } from '../../CommonCss/pagecss'
import { formHead } from '../../CommonCss/formcss'
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)
  const [data, setData] = 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 {
        setCity(city)
        const response = await fetch('http://192.168.1.52: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) {
      sendCity()
    }
  }, [userdata])

  console.log(city)
  return (
    <View style={styles.container}>
      <StatusBar />
      <TopNavbar navigation={navigation} page={"MainPage"} />
      <Bottomnavbar navigation={navigation} page={"MainPage"} />
    </View>
  )
}

export default Mainpage
英文:

How can i fix this error in my project? the error is ERROR TypeError: null is not an object (evaluating 'userdata.user') i am using react native expo after logging into my app and entering mainpage its giving me this error can anyone can help me to fix this error? i today send 8 hours fixing this error but i can't able to fix it can anyone can help me with that?

import { StyleSheet, Text, View, StatusBar } from &#39;react-native&#39;
import React, { useEffect, useState } from &#39;react&#39;
import { containerFull } from &#39;../../CommonCss/pagecss&#39;
import { formHead } from &#39;../../CommonCss/formcss&#39;
import Bottomnavbar from &#39;../../Components/Bottomnavbar&#39;
import TopNavbar from &#39;../../Components/TopNavbar&#39;
import FollowersRandomPost from &#39;../../Components/FollowersRandomPost&#39;
import AsyncStorage from &#39;@react-native-async-storage/async-storage&#39;;
import * as Location from &#39;expo-location&#39;;
const Mainpage = ({ navigation }) =&gt; {
const [userdata, setUserdata] = React.useState(null)
const [location, setLocation] = useState(null);
const [errorMsg, setErrorMsg] = useState(null);
const [city, setCity] = useState(null);
const [data, setData] =  useState(null)
useEffect(() =&gt; {
AsyncStorage.getItem(&#39;user&#39;)
.then(data =&gt; {
// console.log(&#39;async userdata &#39;, data)
setUserdata(JSON.parse(data))
})
.catch(err =&gt; alert(err))
}, [])
console.log(&#39;userdata &#39;, userdata)
useEffect(() =&gt; {
(async () =&gt; {
let { status } = await Location.requestForegroundPermissionsAsync();
if (status !== &#39;granted&#39;) {
setErrorMsg(&#39;Permission to access location was denied&#39;);
}
let location = await Location.getCurrentPositionAsync({});
setLocation(location);
let city = await Location.reverseGeocodeAsync(location.coords);
setCity(city[0].city);
})();
}, []);
const sendCity = () =&gt; {
setCity(city);
fetch(&#39;http://192.168.1.52:3000/updateCity&#39;, {
method: &#39;POST&#39;,
headers: {
&#39;Content-Type&#39;: &#39;application/json&#39;,
},
body: JSON.stringify({
city: city,
username: userdata.user.username
}),
})
.then((response) =&gt; response.json())
.then((data) =&gt; {
console.log(&#39;Success:&#39;, data);
})
.catch((error) =&gt; {
console.error(&#39;Error:&#39;, error);
});
};
useEffect(() =&gt; {
sendCity();
}, [])
return (
&lt;View style={styles.container}&gt;
&lt;StatusBar /&gt;
&lt;TopNavbar navigation={navigation} page={&quot;MainPage&quot;} /&gt;
&lt;Bottomnavbar navigation={navigation} page={&quot;MainPage&quot;} /&gt;
&lt;FollowersRandomPost /&gt;
&lt;/View&gt;
)
}
export default Mainpage
const styles = StyleSheet.create({
container: {
width: &#39;100%&#39;,
height: &#39;100%&#39;,
backgroundColor: &#39;black&#39;,
paddingVertical: 50,
}
})

And why something city value becomes null and something new york which is correct how to fix null?

import { StyleSheet, Text, View, StatusBar } from &#39;react-native&#39;
import React, { useEffect, useState } from &#39;react&#39;
import { containerFull } from &#39;../../CommonCss/pagecss&#39;
import { formHead } from &#39;../../CommonCss/formcss&#39;
import Bottomnavbar from &#39;../../Components/Bottomnavbar&#39;
import TopNavbar from &#39;../../Components/TopNavbar&#39;
import FollowersRandomPost from &#39;../../Components/FollowersRandomPost&#39;
import AsyncStorage from &#39;@react-native-async-storage/async-storage&#39;;
import * as Location from &#39;expo-location&#39;;
const Mainpage = ({ navigation }) =&gt; {
const [userdata, setUserdata] = useState(null);
const [location, setLocation] = useState(null);
const [errorMsg, setErrorMsg] = useState(null);
const [city, setCity] = useState(null);
const [data, setData] =  useState(null);
useEffect(() =&gt; {
async function getUserData() {
try {
const userDataString = await AsyncStorage.getItem(&#39;user&#39;);
const userData = JSON.parse(userDataString);
setUserdata(userData);
} catch (err) {
alert(err);
}
}
getUserData();
}, []);
useEffect(() =&gt; {
async function getLocation() {
try {
let { status } = await Location.requestForegroundPermissionsAsync();
if (status !== &#39;granted&#39;) {
setErrorMsg(&#39;Permission to access location was denied&#39;);
}
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(() =&gt; {
async function sendCity() {
try {
setCity(city);
const response = await fetch(&#39;http://192.168.1.52:3000/updateCity&#39;, {
method: &#39;POST&#39;,
headers: {
&#39;Content-Type&#39;: &#39;application/json&#39;,
},
body: JSON.stringify({
city: city,
username: userdata.user.username
}),
});
const data = await response.json();
console.log(&#39;Success:&#39;, data);
} catch (err) {
console.error(&#39;Error:&#39;, err);
}
}
if (userdata) {
sendCity();
}
}, [userdata]);
console.log(city)
return (
&lt;View style={styles.container}&gt;
&lt;StatusBar /&gt;
&lt;TopNavbar navigation={navigation} page={&quot;MainPage&quot;} /&gt;
&lt;Bottomnavbar navigation={navigation} page={&quot;MainPage&quot;} /&gt;
&lt;/View&gt;
);
}
export default Mainpage

答案1

得分: 1

你需要等待 AsyncStorage 完成其任务,然后再使用新数据,可以考虑使用顶级 await,例如:

useEffect(() => {
  const fetchData = async () => {
    try {
      const data = await AsyncStorage.getItem('user');
      setUserdata(JSON.parse(data));
    } catch (err) {
      alert(err);
    }
  };

  fetchData();
}, []);

console.log('userdata', userdata);

对于第二个问题,如果你在 useEffect 中设置了城市状态并且将其与 userdata 依赖关联,那么当 userdata 状态发生更改时,将触发该函数。由于城市的初始状态为 null,而且在 sendCity 中不能立即获取新的状态,也不能在不重新渲染组件的情况下从 getLocation 中获取新状态,我认为在运行该函数之前需要添加一个额外的条件,但这可能会导致 useEffect 产生一些副作用。

useEffect(() => {
  async function sendCity() {
    try {
      const response = await fetch('http://192.168.1.52: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]);
英文:

You need to wait AsyncStorage to finish his task before using the new data, how about using top lvl await like :

 useEffect(() =&gt; {
await AsyncStorage.getItem(&#39;user&#39;)
.then(data =&gt; {
// console.log(&#39;async userdata &#39;, data)
setUserdata(JSON.parse(data))
})
.catch(err =&gt; alert(err))
}, [])
console.log(&#39;userdata &#39;, userdata)

for the 2nd question if you set city state inside the useEffect and with userdata dependency this will trigger the function when userdata state change, and since city initial state is null, and you can't immediatly get the new state from getLocation neither in sendCity, without rerender your component, i think you need to add one more condition before running the function, but this might have some side effect from the useEffect..

useEffect(() =&gt; { 
async function sendCity() {
try {
const response = await fetch(&#39;http://192.168.1.52:3000/updateCity&#39;, {
method: &#39;POST&#39;,
headers: {
&#39;Content-Type&#39;: &#39;application/json&#39;,
},
body: JSON.stringify({
city: city,
username: userdata.user.username
}),
});
const data = await response.json();
console.log(&#39;Success:&#39;, data);
} catch (err) {
console.error(&#39;Error:&#39;, err);
}
}
if (userdata &amp;&amp; city) {
sendCity();
}
}, [userdata, city]);

huangapple
  • 本文由 发表于 2023年1月8日 01:36:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/75042441.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定