簡體   English   中英

如何訪問 API 的結果以顯示到我的 UI? (反應原生)

[英]How to access results from API to display to my UI? (React Native)

我目前正在 React Native 中的 App 組件內進行 API 調用。 我正在使用 fetch 來捕獲一些值並將它們存儲在我的 fetch 中的變量中。 如何訪問我的 return 語句中的這些變量以顯示到我的 UI?

這就是我的組件現在的樣子,我需要在我的 return 語句中看到“需要數據”的“lessonDesc”和“lessonName”值

export default function App() {



fetch(contentURL).then((response) => response.json()).then((json) => {
  let lessonName = json.fields.lessonName
  console.log(json.fields.lessonName);
  let lessonDesc = json.fields.lessonDesc

  console.log(json.fields.lessonDesc);
  return lessonDesc
}).catch((error) => {
  console.error(error);
})


return (
  
    <View style={styles.container}>
      <Text>{NEED DATA HERE}</Text>
      <StatusBar style="auto" />
    </View>
  );
}```

最好的方法是使用useState更新變量,您可以在組件中訪問該變量,您也可以單獨或一起定義狀態,在這種情況下我們單獨定義。 所以你可以試試:

export default function App() {
   const [lessonName, setLessonName] = React.useState("");
   const [lessonDesc, setLessonDesc] = React.useState("");

   React.useEffect(()=>{
    fetch(contentURL).then((response) => 
      response.json()).then((json) => {
        setLessonName(
          json.fields.lessonName
        );
        setLessonDesc(
           json.fields.lessonDesc
        );
      }).catch((error) => {
        console.error(error);
      })
   } , []);

return (
  
    <View style={styles.container}>
      <Text>{NEED DATA HERE}</Text>
      <StatusBar style="auto" />
    </View>
  );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM