React -在组件加载时获取URL和setState



我正在使用React Native编写一个应用程序我得到了奇怪的错误。我想在"App加载"上获取用户的国家,更新状态,然后在组件的其他地方使用状态。听起来很简单,但我总是出错。

对于这个特定的代码,我得到undefined不是一个对象(求值'this.state').

我做错了什么?我该怎么做才对呢?

(我使用API,因为我不想请求位置权限)

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>
);
}

功能组件没有this。在功能组件中没有this.setState这样的东西。相反,你必须使用useState,而不是使用实例的属性,在函数体中使用一个普通的独立变量(和一个状态设置函数作为另一个独立变量):

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>
);
}

最新更新