简体   繁体   English

React Native Client 无法呈现来自 api 调用的 JSON 数据

[英]React Native Client cannot render JSON data from api call

I am currently trying to make a react native app that shall fetch an api and then render that data.我目前正在尝试制作一个应获取 api 然后呈现该数据的反应本机应用程序。 However it does not work and I do not know what I am doing wrong.但是它不起作用,我不知道我做错了什么。 My API returns an Object that is correctly logged out in my console.我的 API 返回一个在我的控制台中正确注销的 Object。 But in my actual react native app I only get "undefined" displayed if I try to render it.但是在我实际的反应本机应用程序中,如果我尝试渲染它,我只会显示“未定义”。 Apart from that my console says the following even tho i specify a unique key prop in my component:除此之外,即使我在我的组件中指定了一个唯一的关键道具,我的控制台也会说以下内容:

"Warning: Each child in a list should have a unique "key" prop."

Here is my code:这是我的代码:

export default function MyComponent() {

  const myData = fetch('(Right URL from API stands here)', {
    method: 'GET'
  })
  .then(res => res.json())
  .then(data => console.log(data));

    return (
      <View style={styles.container}>
        {
          Object.keys(myData).map(data => {
            return (
              <View key={data.id}>
                  <Text>{"Data: " + data.message}</Text>
              </View>
                
            )
          })
        }
      </View>
    );
  }

  const styles = StyleSheet.create({
    container: {
      flex: 1,
      alignItems: "center",
      marginTop: 48,
    }
  });

    

Here is my console logging out an object after fetching data:这是我的控制台在获取数据后注销 object:

Array [
  Object {
    "message": "This is a message",
    "username": "leon42",
    "id": 1,
    "timing": "2022-01-01T12:00:00.000Z",
  },
  Object {
    "message": "This is a message",
    "username": "henry42",
    "id": 2,
    "timing": "2022-01-01T12:00:00.000Z",
  },
  Object {
    "message": "This is a message",
    "username": "pauli42",
    "id": 3,
    "timing": "2022-01-01T12:00:00.000Z",
  },
]

My Component then looks like this on my phone:我的组件在我的手机上看起来像这样: 在此处输入图像描述

Your fetch is async, thus in your first render cycle the data is undefined .您的fetch是异步的,因此在您的第一个渲染周期中dataundefined The reason why it is defined in your log message is because you are using a then chain.它在您的日志消息中定义的原因是因为您使用的是then链。 However, since the render cycle is already finished, the screen won't react on the updated information.但是,由于渲染周期已经完成,屏幕不会对更新的信息做出反应。

Create a state and update the state once the API call returns its data.创建一个 state 并在 API 调用返回其数据后更新 state。 The state change will cause a rerendering. state 更改将导致重新渲染。

export default function MyComponent() {

  const [data, setData] = useState()

  React.useEffect(() => {
     const fetchData = async () => {
        
         const d = await fetch('(Right URL from API stands here)', {
                method: 'GET'
         })
        setData(d)
     }
     
     fetchData()
  }, [])

    return (
      <View style={styles.container}>
        {
          Object.keys(data).map(item => {
            return (
              <View key={item.id}>
                  <Text>{"Data: " + item.message}</Text>
              </View>
                
            )
          })
        }
      </View>
    );
  }

  const styles = StyleSheet.create({
    container: {
      flex: 1,
      alignItems: "center",
      marginTop: 48,
    }
  });

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

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