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 是正确的(无论如何都应该捕获错误)。
最佳答案
问题:
Feeds
返回一个 promise ,因此您不能将 is 用作Feeds.map(...)
。无论您在
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/