繁体   English   中英

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

[英]React - Fetch from URL and setState on component load

我正在使用React Native编写应用程序,但出现奇怪的错误。 我想在“应用程序加载”上获取用户的国家/地区,更新 state,然后在组件的其他地方使用 state。 听起来很简单,但我总是出错。

对于这个特定的代码,我得到undefined is not an object (evaluation '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 ,而不是使用实例的属性,而是在 ZC1C425268E687385D1AB50711C

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM