简体   繁体   English

React-Native:解析JSON

[英]React-Native: Parsing JSON

feed.js 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;

data.js data.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));
  });
}

Now this throws out that feedData is not defined. 现在,这表明没有定义feedData。 Why exactly is that? 为什么会这样呢? Also i've tried another way of showing the data (see below) but that also ends up in errors. 我也尝试了另一种显示数据的方式(见下文),但最终也会出错。

Attempt: 尝试:

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

The json returned from the site is correct (and errors should be catched anyway). 从站点返回的json是正确的(无论如何都应该捕获错误)。

Issues: 问题:

  1. Feeds returns a promise and so you cannot use is as Feeds.map(...) . Feeds返回了Feeds.map(...) ,因此您不能将其作为Feeds.map(...)

  2. Whatever you are doing in Get is unnecessary as fetch returns a promise, and Get adds another promise wrapper. 您在Get中所做的任何操作都是不必要的,因为fetch返回一个Promise,而Get添加另一个Promise包装器。 Also fetch is capable of throwing appropriate errors. 而且fetch能够引发适当的错误。

I assume parsing response based on response type is the only reason for making Get function, try following 我假设基于响应类型解析响应是制作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}`));
}

Please try following snippet for rendering data: 请尝试按照以下代码段呈现数据:

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>
    );
  }
}

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

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