javascript - React-Native:解析 JSON

标签 javascript json react-native promise

feed.js

import React, { Component } from 'react';
import {
  Text,
  View,
  ScrollView,
  StyleSheet,
  Image
} from 'react-native';
import { List, ListItem } from 'react-native-elements';
import { Feeds } from '../config/data';

const styles = StyleSheet.create({
  logo: {
    marginLeft: 145,
    marginTop: 35,
    tintColor: '#2ecc71'
  }
});

console.log(Feeds);

class Feed extends Component {
  render() {
    return (
      <ScrollView>
        <Image style={styles.logo} source={require('../img/Logo.png')} />
        <List>
            Feeds.map(function(feedData) {
                <ListItem
                key={feedData.id}
                title={feedData.title}
                subtitle={feedData.content}
                />
            });
        </List>
      </ScrollView>
    );
  }
}

export default Feed;

数据.js

export const Feeds = Get('http://example.de/api.php');

function Get(url) {
  return fetch(url).then(response => {
    if (response.ok) {
      const contentType = response.headers.get('Content-Type') || '';

      if (contentType.includes('application/json')) {
        return response.json().catch(error => {
          return Promise.reject(new ResponseError('Error: ' + error.message));
        });
      }
    }
  }).catch(error => {
    return Promise.reject(new NetworkError(error.message));
  });
}

现在这会抛出 feedData 未定义的情况。到底是为什么呢?我还尝试了另一种显示数据的方法(见下文),但最终也会出现错误。

尝试:

            Feeds.then(response => {
                {response.map((feed) => (
                    <ListItem
                    key={feed.id}
                    title={feed.title}
                    subtitle={feed.content}
                    />
                 ))}
            });

从站点返回的 json 是正确的(无论如何都应该捕获错误)。

最佳答案

问题:

  1. Feeds 返回一个 promise ,因此您不能将 is 用作 Feeds.map(...)

  2. 无论您在 Get 中做什么都是不必要的,因为 fetch 返回一个 Promise,而 Get 添加另一个 Promise 包装器。此外,fetch 能够抛出适当的错误。

我假设根据响应类型解析响应是创建 Get 函数的唯一原因,请尝试以下操作

function Get2(url) {
  return fetch(url).then(response => {
    const contentType = response.headers.get('Content-Type') || '';

    if (contentType.includes('application/json')) {
      return response.json().catch(error => Promise.reject(`ResponseError: ${error.message}`))
    }
    // Check for other content type, its better to convert to json, as above returns json

  }).catch(error => Promise.reject(`NetworkError: ${error.message}`));
}

请尝试以下代码片段来渲染数据:

class App extends React.Component {

  constructor(props) {
    super(props)
    this.state = {
      feeds: []
    }

    this.fetchFeeds = this.fetchFeeds.bind(this)
  }

  componentDidMount() {
    this.fetchFeeds()
  }

  fetchFeeds() {
    Feeds.then(res => {
      this.setState({
        feeds: res
      })
    }).catch(err => {
      console.log(err)
    })
  }

  render() {
    return (
      <ScrollView>
        <Image style={styles.logo} source={require('../img/Logo.png')} />
        <List>
            {this.state.feeds.map( feedData => {
                return <ListItem
                key={feedData.id}
                title={feedData.title}
                subtitle={feedData.content}
                />
            })}
        </List>
      </ScrollView>
    );
  }
}

关于javascript - React-Native:解析 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44108094/

相关文章:

javascript - Mozilla AFRAME a-frame 通过按钮单击而不是击键启动检查器

javascript - 使用 Javascript 在导航栏中显示当前选项卡

css - react-native 风格的 iframe 以适应 webview

react-native - 在 React Native 中绘制水平线

javascript - 尝试在操作中使用异步代码时的最佳实践

javascript - 遍历列表并插入对象数组

javascript - 如何在 DIV 中显示 JSON 响应的错误?

java - JsonException java.lang.String 类型的值 stdClass 无法转换为 JSONObject?

javascript - Web:在进行缓慢的服务器端调用后,我们如何在客户端上显示内容?

json - 常规.json.JsonException : expecting '}' or ',' but got current char