【问题标题】:Return JSON and print out reactJS返回 JSON 并打印出 reactJS
【发布时间】:2019-08-03 04:36:49
【问题描述】:

你会认为从 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 |     });

我该如何解决这个问题?

【问题讨论】:

  • 注释掉有.map的那一行,去掉错误,加上console.log(this.state.data),看看是不是数组
  • @MoIsmat 以下工作的 console.log(this.state.data.news);但是我如何打印它(foreach?)
  • @RussellHarrower 能否提供控制台登录时在 this.state.data 中获得的内容

标签: json reactjs axios


【解决方案1】:

假设您正在获取数据。确保您的数据应该是 Array 而不是字符串

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

添加这个

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

        {this.renderData}

        </Container>
      );
    }

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-01
      • 2017-08-21
      • 2022-11-12
      • 2020-01-23
      • 2018-08-12
      • 2019-06-09
      • 2016-05-23
      相关资源
      最近更新 更多