首页 > 解决方案 > 返回 JSON 并打印出 reactJS

问题描述

您会认为从 JSON 文件返回数据很简单,但是我的尝试失败了。

基本概念如下

class News extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            data: []
        };
    }

    componentDidMount() {
        axios.get('http://api.drn1.com.au/api-access/news')
        .then(({ data })=> {
            this.setState({
                data: data
            });
        });
    }

    render() {
      return (
        <Container maxWidth="lg">
        <Helmet>
            <meta charSet="utf-8" />
            <title>DRN1 :: Latest News</title>
            <link rel="canonical" href={document.location} />
        </Helmet>
        <ComingSoon />

        {this.state.data.map(news => <div>{news.title+' '+news.url}</div>)}

        </Container>
      );
    }
  }

  export default News;

但是,它似乎正在引发错误。

TypeError: this.state.data.map is not a function
News.render
src/components/News.js:67
  64 |     <title>DRN1 :: Latest News</title>
  65 |     <link rel="canonical" href={document.location} />
  66 | </Helmet>
> 67 | <ComingSoon />
     | ^  68 | 
  69 | {this.state.data.map(news => <div>{news.title+' '+news.url}</div>)}
  70 | 
View compiled
▶ 17 stack frames were collapsed.
(anonymous function)
src/components/News.js:53
  50 | componentDidMount() {
  51 |     axios.get('http://api.drn1.com.au/api-access/news')
  52 |     .then(({ data })=> {
> 53 |         this.setState({
     | ^  54 |             data: data
  55 |         });
  56 |     });

我怎样才能解决这个问题?

标签: jsonreactjsaxios

解决方案


axios.get(' http://api.drn1.com.au/api-access/news ') 返回如下:

{'news': [{}, {}, ...]}

所以你应该迭代 data.news,而不是数据。


推荐阅读