【问题标题】:React Native, calling on functionsReact Native,调用函数
【发布时间】:2016-11-13 19:35:40
【问题描述】:

我有一个反应原生的功能

 _onPressButtonGET: function() {
    fetch("https://newsapi.org/v1/articles?source=techcrunch&apiKey=[YOUR_API_KEY]", {method: "GET"})
    .then((response) => response.json())
    .then((responseData) => {
//             AlertIOS.alert(
//                  "Latest Story: TechCrunch",
//                 "" + responseData.articles[0].title
//             )
responseData.articles[0].title
    })
    .done();
},

我正在尝试在组件中获取文章标题,但在这样做时遇到了麻烦。我怎样才能做到这一点?谢谢!

【问题讨论】:

    标签: json react-native


    【解决方案1】:

    首先,您需要定义一个状态,该状态将存储您的标题。您可以使用类属性来做到这一点:

    class TitleExample extends Component {
    
      state = { title: "" };
    
    }
    

    然后你需要调用你的 fetch 函数。您可以在componentWillMount 中执行此操作,因此将在组件安装之前获取数据:

    class TitleExample extends Component {
    
      state = { title: "" };
    
      componentWillMount() {
        fetch("https://newsapi.org/v1/articles?source=techcrunch&apiKey=[YOUR_API_KEY]")
        .then((response) => response.json())
        .then((responseData) => this.setState({ title: responseData.articles[0].title }));
      }
    
    }
    

    最后你可以渲染你的标题了:

    class TitleExample extends Component {
    
      state = { title: "" };
    
      componentWillMount() {
        fetch("https://newsapi.org/v1/articles?source=techcrunch&apiKey=[YOUR_API_KEY]")
        .then((response) => response.json())
        .then((responseData) => this.setState({ title: responseData.articles[0].title }));
      }
    
      render() {
        return (
          <View>
            <Text>{this.state.title}</Text>
          </View>
        );
      }
    
    }
    

    你正在做一些非常基本的事情,特别是与 React Native 无关,所以我建议你阅读 React 网站上的state docs

    编辑:

    我要渲染所有文章,你可以把它们全部存储在状态中,然后在渲染中循环遍历:

    class TitleExample extends Component {
    
      state = { articles: [] };
    
      componentWillMount() {
        fetch("https://newsapi.org/v1/articles?source=techcrunch&apiKey=[YOUR_API_KEY]")
        .then((response) => response.json())
        .then((responseData) => this.setState({ articles: responseData.articles }));
      }
    
      render() {
        return (
          <View>
            {this.state.articles.map(article => (
              <Text>{article.title}</Text>
            ))}
          </View>
        );
      }
    
    }
    

    【讨论】:

    • 好的,谢谢!! @Kerumen 那么我如何能够遍历 JSON 中的所有项目而不是只调用第一个项目,是否有 .each 之类的东西?
    猜你喜欢
    • 2016-12-26
    • 1970-01-01
    • 2019-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-24
    相关资源
    最近更新 更多