简体   繁体   English

在本机反应中渲染来自 JSON 的数据

[英]Render data from JSON in react native

im trying to render these JSON data but I cant access company at all.I cant figure out where is the problem?我试图渲染这些 JSON 数据,但我根本无法访问公司。我不知道问题出在哪里? This is the JSON:这是 JSON:

[
{
   "address": {
       "country": "Albania",
       "city": "Tirana",
       "street": "Sheshi Skenderbe"
   },
   "_id": "5fc96784e740aaa9af2139ae",
   "company": "Big market",
   "phone": "+35568123456"
}
]

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

const [data, setData] = useState([]);
  useEffect(() => {
    (async () => {
      try {
        const response = await axiosApiInstance.get(`/companies/list/1`);
        setData(response.data);
        console.log(response.data, "Data from Furnitoret");
      } catch (err) {
        Alert.alert("Mesazhi", err.response.data.message);
      }
    })();
  }, []);

and the render和渲染

 <FlatList
        keyExtractor={(item, i) => i.toString()}
        data={data}
        renderItem={({ item, i }) => (
          <Card
            title={data.company}
            onPress={() => navigation.navigate("Porosia")}
          />
        )}
      />

Within your renderItem prop of the flatlist, you giving the name item to each element in the data array, but then you are trying to use your data object which is the complete list, instead of the current item .在平面列表的 renderItem 属性中,您将名称item赋予data数组中的每个元素,但随后您尝试使用数据 object ,这是完整列表,而不是当前item

It should be它应该是

      <FlatList
        keyExtractor={(item, i) => item._id}
        data={data}
        renderItem={({ item, i }) => (
          <Card
            title={item.company} // <----------------- item not data
            onPress={() => navigation.navigate("Porosia")}
          />
        )}
      />

Also, as a side note you might want to use the company id as the key instead of the array index, as you might run into performance problems when updating this list later on此外,作为旁注,您可能希望使用公司 ID 作为键而不是数组索引,因为稍后更新此列表时可能会遇到性能问题

keyExtractor={(item, i) => item._id}

change data.company to item.company likedata.company更改为item.company类的

<Card
    title={item.company}
/>

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

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