【发布时间】:2018-09-04 15:33:29
【问题描述】:
我正在尝试实现一个新闻应用程序。它应该以缩略图和描述开头的新闻标题列表显示,然后单击该 URL 应在浏览器中打开。但是,我被困在中途遇到类型错误。
这是我的 NewsList 和 NewsDetail 文件的代码。
NewsList.js
import React, { Component } from 'react';
import { ScrollView } from 'react-native';
import axios from 'axios';
import NewsDetail from './NewsDetail';
class NewsList extends Component {
constructor(props) {
super(props);
this.state = {
news: []
};
}
//state = {news: []};
componentWillMount() {
axios.get('https://newsapi.org/v2/top-headlines?country=in&apiKey=MYAPIKEY')
.then(response => this.setState({news: response.data }));
}
renderNews() {
return this.state.news.map(newsData =>
<NewsDetail key={newsData.title} newsData={newsData} />
);
}
render() {
console.log("something",this.state);
return (
<ScrollView>
{this.renderNews()}
</ScrollView>
);
}
}
export default NewsList;
NewsDetail.js
import React from 'react';
import { Text, View, Image, Linking } from 'react-native';
import Card from './Card';
import CardSection from './CardSection';
import Button from './Button';
import NewsList from './NewsList';
const NewsDetail =({ newsData }) => {
const { title, description, thumbnail_image, urlToImage, url } = newsData;
const { thumbnailStyle,
headerContentStyle,
thumbnailContainerStyle,
headerTextStyle,
imageStyle } =styles;
return(
<Card>
<CardSection>
<View>
<Image
style={thumbnailStyle}
source={{uri: urlToImage}}
/>
</View>
<View style={headerContentStyle}>
<Text style={headerTextStyle}>{title}</Text>
<Text>{description}</Text>
</View>
</CardSection>
<CardSection>
<Image
style={imageStyle}
source={{uri:urlToImage}}
/>
</CardSection>
<CardSection>
<Button onPress={() =>Linking.openURL(url)} >
ReadMore
</Button>
</CardSection>
</Card>
);
};
export default NewsDetail;
我遇到的错误的 StackTrace
TypeError: this.state.news.map 不是函数
此错误位于: 在新闻列表中(在 App.js:11) 在 RCTView 中(在 View.js:78) 在视图中(在 App.js:9 处) 在应用程序中(在 renderApplication.js:35) 在 RCTView 中(在 View.js:78) 在视图中(在 AppContainer.js:102) 在 RCTView 中(在 View.js:78) 在视图中(在 AppContainer.js:122) 在 AppContainer 中(在 renderApplication.js:34 处)NewsList.renderNews NewsList.js:21:31 NewsList.proxiedMethod createPrototypeProxy.js:44:29 NewsList.render NewsList.js:31:18 NewsList.proxiedMethod createPrototypeProxy.js:44:29 finishClassComponent ReactNativeRenderer-dev.js:8707:30 updateClassComponent ReactNativeRenderer-dev.js:8674:11 beginWork ReactNativeRenderer-dev.js:9375:15 performUnitOfWork ReactNativeRenderer-dev.js:11771:15 workLoop ReactNativeRenderer-dev.js:11839:25 Object.invokeGuardedCallback ReactNativeRenderer-dev.js:39:9
App.js
import React from 'react';
import { AppRegistry, View } from 'react-native';
import Header from './header';
import NewsList from './NewsList';
//create component
const App = () => {
return(
<View style={{ flex:0 }}>
<Header headerText={'Headlines'} />
<NewsList />
</View>);
}
export default App;
AppRegistry.registerComponent('news', () => App);
【问题讨论】:
标签: json react-native axios