【问题标题】:Extracting data from json object from API with JavaScript React Native使用 JavaScript React Native 从 API 的 json 对象中提取数据
【发布时间】:2018-12-29 15:15:15
【问题描述】:

我有一个从新闻 API 中获取的 json 对象,我想打印出其中一篇文章的作者。我想知道如何在我称之为“作者”的反应组件中做到这一点。

这是 json 对象:这里包含的内容太长,但有链接供您查看。

可从https://newsapi.org/ 访问,共有 20 篇文章。

我有这个反应组件,我正在尝试打印该文章的一位作者:

import React, { Component } from 'react';

const APIurl = 'https://newsapi.org/v2/top-headlines? 
country=it&apiKey=0b3e87958d0b4e71a9e2ed3eea69237a';

class Author extends Component {
    constructor(props) {
        super(props);
        this.state = {};
    }

    componentDidMount() {
        fetch(APIurl)
            .then(response => response.json())
            .then(response => {
                this.setState({
                    articles: response
                })
            })
    }

    render() {
        return (
            <h5 class="f6 ttu tracked black-80">
                {this.state.articles.article[0].author}
            </h5>
       );
   }
}

export default Author;

但是,有些事情一定不太正确,因为我收到了这个错误:

TypeError: Cannot read property 'articles' of undefined

 21 | render() {
 22 |   return (
 23 |       <h5 class="f6 ttu tracked black-80">
> 24 |          {this.state.articles.articles[0].author}
 25 |       </h5>
 26 |   );
 27 | }

我不确定我做错了什么。也很抱歉 json 对象的格式不好。

在看到下面的建议后,我现在做了一些更改,因此我的代码如下所示:

import React, { Component } from 'react';

const APIurl = 'https://newsapi.org/v2/top-headlines?       country=it&apiKey=0b3e87958d0b4e71a9e2ed3eea69237a';

class Author extends Component {
    constructor(props) {
        super(props);
        this.state = {
            articles: []
        };
    }

    componentDidMount() {
        fetch(APIurl)
            .then(response => response.json())
            .then(response => {
                this.setState({
                    articles: response
                })
            })
    }

    render() {
        const { articles } = this.state;
        return (
            <h5 class="f6 ttu tracked black-80">
                {articles.length>0 && articles.articles[1].author}
            </h5>
        );
    }
}

export default Author;

然而,它仍然没有打印出作者反应组件中的任何内容,即使当我转到 chrome 开发人员工具并查看组件的状态时,它看起来像这样:

State
    articles: {…}
        articles: Array[20]
            0: {…}
            1: {…}
                 author: "Davide Stoppini"
                 description: "A Pisa, divertente pareggio con i russi, più avanti per quanto riguarda la condizione fisica. Passi in avanti rispetto al Sion: bene gli esterni offensivi, anche i due attaccanti confermano la confide…"
                 publishedAt: "2018-07-21T20:20:21Z"
                 source: {…}
                 title: "Inter, fuochi d'artificio con lo Zenit: è 3-3. In gol Icardi e Lautaro"
                 url: "https://www.gazzetta.it/Calcio/Serie-A/Inter/21-07-2018/inter-fuochi-d-artificio-lo-zenit-3-3-gol-icardi-lautaro-280799153444.shtml"
                  urlToImage:"https://images2.gazzettaobjects.it/methode_image/2018/07/21/Calcio/Foto%20Calcio%20-%20Trattate/1d50f03c94d965c2ca84bd3eec0137c9_169_xl.jpg

*注意:这只是显示文章数组的第一个第二个元素。

【问题讨论】:

    标签: json reactjs api object


    【解决方案1】:

    基本上,您必须首先将文章声明为空数组,如下所示:

    this.state = {
       articles: []
    };
    

    并且还需要修改render里面的代码如下:

    {this.state.articles && (this.state.articles.article.length>0) &&
    this.state.articles.article[0].author
    }
    

    希望对你有帮助。

    【讨论】:

      【解决方案2】:

      您遇到的问题是因为您的代码没有准备好通过 React 的生命周期。在您获得componentDidMount 阶段的数据之前,有一个渲染阶段,这就是发生错误的地方。在那个渲染阶段articles 应该是一个没有数据的空数组,然后你需要检查以避免在数组为空时渲染任何东西。因此,为了避免在componentDidMount 阶段之前的render 阶段出现该错误,您需要在状态中设置一个名为articles 的空数组,并在渲染方法中检查它是否不为空,以渲染该值你想要的。

      import React, { Component } from 'react';
      
      const APIurl = 'https://newsapi.org/v2/top-headlines? 
      country=it&apiKey=0b3e87958d0b4e71a9e2ed3eea69237a';
      
      class Author extends Component {
          constructor(props) {
              super(props);
              this.state = { articles: []};
          }
      
          componentDidMount() {
              fetch(APIurl)
                  .then(response => response.json())
                  .then(response => {
                      this.setState({
                          articles: response.articles
                      })
                  })
          }
      
          render() {
            const { articles } = this.state;
              return (
                  <h5 class="f6 ttu tracked black-80">
                      {articles.length > 0 && articles[0].author}
                  </h5>
             );
         }
      }
      
      export default Author;
      

      【讨论】:

      • 感谢您的建议。我已经对我的代码进行了一些更改以执行您的建议,但它仍然没有在作者反应组件中打印出任何内容。我在帖子中添加了更多信息,以防万一。
      • 您错过了获取响应中的部分,我只剩下将响应对象的articles 属性保存为this.state.articles。如果你仍然对如何访问你保存在状态中的数据有疑问,在渲染方法中状态解构后设置一个console.log(articles)const { articles } = this.state;),你将看到你必须如何访问数据。
      【解决方案3】:

      React Native 中的新闻应用:

      const SITE_URL =
        "https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=a39bbc7131c649a3ad23fe79063d996f";
      
      const TestScreen = () => {
       
      
        const [myData, setMyData] = useState();
        useEffect(() => {
          axios
            .get(SITE_URL)
            .then((res) => {
              // console.log("Response from main API: ", res);
              console.log(
                "-----------------------------------------------------------  Start"
              );
      
              // console.log("Response from Home Data Data: ", res.data.data);
              console.log(
                "Response from NEWS data articles: ",
                res.data.articles
              );
              console.log(
                "-----------------------------------------------------------  End"
              );
              // let companyData = res.data.data;
              let companyData = res.data.articles;
              setMyData(companyData);
      
              setData({
                Company: companyData,
                Description: "",
              });
            })
            .catch((err) => {
              console.log(err);
            });
        }, []);
        //   console.log("myData:", { myData });
        const renderItem = ({ item, index }) => (
          <TouchableOpacity style={styles.container}>
            <Text style={styles.title}>
              {index}. {item.author}
            </Text>
            <Text> {item.description} </Text>
            <View>
              <Image
                style={{
                  width: 500,
                  height: 100,
                }}
                source={{
                  uri: item.urlToImage,
                }}
              />
            </View>
          </TouchableOpacity>
        );
      
        return (
          <View style={styles.container}>
            <Text>Read Later Screen</Text>
            <Text>|</Text>
            {<FlatList data={myData} renderItem={renderItem} />}
          </View>
        );
      };
      const styles = StyleSheet.create({
        container: {
          flex: 1,
          backgroundColor: "#fff",
          alignItems: "center",
          justifyContent: "center",
        },
      });
      
      export default TestScreen;
      
      

      【讨论】:

        猜你喜欢
        • 2016-11-22
        • 1970-01-01
        • 2017-07-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-26
        • 1970-01-01
        • 2020-06-02
        相关资源
        最近更新 更多