如何传递响应数据到 React Native?

huangapple go评论58阅读模式
英文:

How to pass response data React Native?

问题

I have a service result like this:

object inside array inside object.

So, If I need to single data I can use response.data.data[0].id It is work.(Not dynamically.) But when I set the response.data.data on state state got an error. (object value.)

API POSTMAN result:

{
    "data": [
        {
            "id": 640191,
            "name": "x",
        },
        {
            "id": 640194,
            "name": "y",
        }
    ]
}

I use this service a.js and I need the show list data on b.js

英文:

I have a service result like this:

object inside array inside object.

So, If I need to single data I can use response.data.data[0].id It is work.(Not dynamically.) But when I set the response.data.data on state state got an error. (object value.)

API POSTMAN result:

{
    "data": [
        {
            "id": 640191,
            "name": "x",
        },
        {
            "id": 640194,
            "name": "y",
        }
    ]
}

I use this service a.js and I need the show list data on b.js

答案1

得分: 0

你试图将整个响应数据设置为一个状态变量。如果响应数据是一个对象数组,你应该能够将其设置为一个状态变量而不会出现任何问题。

const [data, setData] = useState([]);

useEffect(() => {
  fetch('your-api-url')
    .then(response => response.json())
    .then(data => setData(data.data));
}, []);

data 是一个状态变量,用于保存响应数据,而 setData 是更新它的函数。useEffect 钩子在组件挂载时运行一次,它从 API 获取数据,将响应转换为 JSON,然后将数据状态变量设置为响应数据的 data 属性。

如果在尝试设置状态时出现错误,可能是因为响应数据的格式与你预期的不同。你应该检查响应数据的实际结构,确保它与你的预期相匹配。你可以通过将响应数据记录到控制台来进行这个检查:

fetch('your-api-url')
  .then(response => response.json())
  .then(data => {
    console.log(data);
    setData(data.data);
  });

如果错误消息提到了 "object value",那可能是因为你尝试在 JSX 中直接渲染数据数组,这是不允许的,因为 JSX 不能直接渲染对象。你需要遍历数组并逐个渲染每个项目。例如:

return (
  <View>
    {data.map(item => (
      <Text key={item.id}>{item.name}</Text>
    ))}
  </View>
);

这段代码遍历数据数组,并为每个项目渲染一个 div,其中项目的名称作为内容。key 属性设置为项目的 id,以为每个项目提供一个唯一的键。

英文:

You're trying to set the entire response data to a state variable. If the response data is an array of objects, you should be able to set it to a state variable without any issues.

const [data, setData] = useState([]);

useEffect(() =&gt; {
  fetch(&#39;your-api-url&#39;)
    .then(response =&gt; response.json())
    .then(data =&gt; setData(data.data));
}, []);

data is a state variable that will hold the response data, and setData is the function to update it. The useEffect hook runs once when the component mounts, and it fetches the data from the API, converts the response to JSON, and then sets the data state variable to the data property of the response data.

If you're getting an error when trying to set the state, it might be because the response data is not in the format you're expecting. You should check the actual structure of the response data to make sure it matches what you're expecting. You can do this by logging the response data to the console:

fetch(&#39;your-api-url&#39;)
  .then(response =&gt; response.json())
  .then(data =&gt; {
    console.log(data);
    setData(data.data);
  });

If the error message mentions "object value", it might be because you're trying to render the data array directly in your JSX, which you can't do because JSX can't render objects directly. You need to map over the array and render each item individually. For example:

return (
  &lt;View&gt;
    {data.map(item =&gt; (
      &lt;Text key={item.id}&gt;{item.name}&lt;/Text&gt;
    ))}
  &lt;/View&gt;
);

This code maps over the data array and renders a div for each item, with the item's name as the content. The key prop is set to the item's id to give each item a unique key.

答案2

得分: -1

以下是已翻译的内容:

  1. useEffect 钩子被用来在组件挂载时触发 fetchData 函数。

  2. fetchData 函数使用 fetch 函数向服务器端点 (https://api.example.com/data) 发起 HTTP GET 请求,将响应数据作为 JSON 检索。然后使用 setData 函数将数据设置到组件状态中。

  3. 该组件呈现一个带有 FlatList 组件的 View 容器,该组件以数据数组作为数据源,以 renderListItem 函数作为项渲染器。

  4. 每个项目都使用一个包含 Text 组件的 View 来显示名称和描述。

注意:不要忘记添加 keyExtractor 函数以生成每个项目的唯一键。

您可以阅读并尝试使用 FlatList 组件

希望这对您有所帮助。

英文:

You first need to fetch the data and store the response in the state, here's a quick example:

import React, { useEffect, useState } from &#39;react&#39;;
import { View, Text, FlatList } from &#39;react-native&#39;;

const MyComponent = () =&gt; {
  const [data, setData] = useState([]);

  useEffect(() =&gt; {
    fetchData();
  }, []);

  const fetchData = async () =&gt; {
    try {
      const response = await fetch(&#39;https://api.example.com/data&#39;);
      const jsonData = await response.json();
      setData(jsonData);
    } catch (error) {
      console.error(&#39;Error fetching data:&#39;, error);
    }
  };

  const renderListItem = ({ item }) =&gt; (
    &lt;View style={{ padding: 10 }}&gt;
      &lt;Text&gt;{item.name}&lt;/Text&gt;
      &lt;Text&gt;{item.description}&lt;/Text&gt;
    &lt;/View&gt;
  );

  return (
    &lt;View style={{ flex: 1, paddingTop: 20 }}&gt;
      &lt;FlatList
        data={data}
        renderItem={renderListItem}
        keyExtractor={(item) =&gt; item.id.toString()}
      /&gt;
    &lt;/View&gt;
  );
};

export default MyComponent;
  1. The useEffect hook is used to trigger the fetchData function when the component mounts.

  2. The fetchData function uses the fetch function to make an HTTP GET request to the server endpoint (https://api.example.com/data) and retrieves the response data as JSON. The data is then set to the component state using the setData function.

  3. The component renders a View container with a FlatList component that takes the data array as the data source, the renderListItem function as the item renderer.

  4. Each item is rendered with a View containing Text components to display the name and description.

Note: Don't forget to add keyExtractor function to generate unique keys for each item.

You can read about and play around with the FlatList component

Hope this helps.

huangapple
  • 本文由 发表于 2023年6月12日 16:15:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76454713.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定