【问题标题】:Handling JSON response React Native处理 JSON 响应 React Native
【发布时间】:2020-05-24 16:31:41
【问题描述】:

我正在关注从 API (https://reactnative.dev/docs/network) 获取 JSON 的 React Native 文档。我是新手,想通过其 API 获取 wordpress 帖子列表,但他们使用的示例非常简单,结构与从 WP 返回对象的方式不同。

我遇到的问题是它正在返回 JSON,但我不确定如何引用我想在我的平面列表中显示的每个项目。问题的线是;

.then((json) => setData(json.movies))

对于这个 WP 返回的 JSON,没有电影(显然),在没有可参考点的情况下,我会指定什么?

我的代码;

import React, { useEffect, useState } from 'react';
import { ActivityIndicator, FlatList, Text, View } from 'react-native';

export default App = () => {
  const [isLoading, setLoading] = useState(true);
  const [data, setData] = useState([]);

  useEffect(() => {
    fetch('https://public-api.wordpress.com/wp/v2/sites/derbyfutsal.com/posts')
      .then((response) => response.json())
      .then((json) => setData(json.movies))
      .catch((error) => console.error(error))
      .finally(() => setLoading(false));
  }, []);

  return (
    <View style={{ flex: 1, padding: 24 }}>
      {isLoading ? <ActivityIndicator/> : (
        <FlatList
          data={data}
          keyExtractor={({ id }, index) => id}
          renderItem={({ item }) => (
            <Text>{item.title}, {item.excerpt}</Text>
          )}
        />
      )}
    </View>
  );
};

【问题讨论】:

    标签: json react-native


    【解决方案1】:

    您不必指定任何内容,您可以直接将响应设置为状态值并在 flatlist 中使用。 我更新了代码以显示 id 而不是标题作为它的对象。您可以随意更改并使用它。

    const App = () => {
      const [isLoading, setLoading] = useState(true);
      const [data, setData] = useState([]);
    
      useEffect(() => {
        fetch('https://public-api.wordpress.com/wp/v2/sites/derbyfutsal.com/posts')
          .then((response) => response.json())
          .then((json) => {
            setData(json)
            })
          .catch((error) => console.error(error))
          .finally(() => setLoading(false));
      }, []);
    
      return (
        <View style={{ flex: 1, padding: 24 }}>
          {isLoading ? <ActivityIndicator/> : (
            <FlatList
              data={data}
              keyExtractor={({ id }, index) => id}
              renderItem={({ item }) => (
                <Text>{item.id}</Text>
              )}
            />
          )}
        </View>
      );
    };
    

    【讨论】:

    • 感谢@Gureparan 的回复,它不喜欢 const App = () => {,但适用于 export default App = () => {,但它有效 ?,我现在将研究如何使用 JSON 的 objects 元素:)。再次感谢
    猜你喜欢
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多