英文:
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 '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,
}
})
And why something city value becomes null and something new york which is correct how to fix null?
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
答案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(() => {
await AsyncStorage.getItem('user')
.then(data => {
// console.log('async userdata ', data)
setUserdata(JSON.parse(data))
})
.catch(err => alert(err))
}, [])
console.log('userdata ', 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(() => {
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]);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论