【问题标题】:React-Native: Type Error when parsing JSONReact-Native:解析 JSON 时出现类型错误
【发布时间】: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


    【解决方案1】:

    您实际上可以在浏览器中转到https://newsapi.org/v2/top-headlines?country=in&apiKey="MY_API_KEY" 或使用curl 或Postman 之类的工具来检查响应是什么。数据响应是一个对象,但您需要一个数组。 articles 很可能是您想要的属性。

    您可能还想检查这是一个数组并适当地更新显示的内容。

    .then(response => {
      const news = response.data.articles;
      if (Array.isArray(news)) {
        this.setState({ news });
      } else {
        this.setState({ errorMessage: 'Could not load any articles' });
      }
    });
    

    【讨论】:

      【解决方案2】:

      您遇到的错误 - TypeError: this.state.news.map is not a function,表示新闻不是数组。
      通过检查您的 api 响应,您应该这样做:
      this.setState({news: response.data.articles })

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-03-31
        • 1970-01-01
        • 2017-10-21
        • 1970-01-01
        • 1970-01-01
        • 2020-02-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多