I am writing an app using React Native and I get weird errors. I would like to fetch the country of the user on "App load", update the state and then to use the state elsewhere in the component. Sounds simple but I get errors all the time.
For this specific code I get undefined is not an object (evaluating 'this.state') .
What am I doing wrong? How should I do it the right way?
(I use an API because I do not want to ask for location permissions).
export default function App() {
state = {
countryCode: 'US',
}
useEffect(() => {
fetch('https://ipapi.co/json/')
.then(response => response.json())
.then(data => this.setState({ countryCode: data.country_code }));
}, []);
return (
<View style={styles.container}>
// ...
</View>
);
}
Functional components do not have this
. There is no such thing as this.setState
in a functional component. Instead, you have to use useState
, which, rather than using a property of an instance, uses a plain standalone variable (and a state setter function as another standalone variable) in the function body:
export default function App() {
const [countryCode, setCountryCode] = useState('US');
useEffect(() => {
fetch('https://ipapi.co/json/')
.then(response => response.json())
.then(data => setCountryCode(data.country_code));
}, []);
return (
<View style={styles.container}>
// ...
</View>
);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.