簡體   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