首页 > 解决方案 > 获取数据反应原生

问题描述

如果有人问过这个问题,我很抱歉,我在反应原生方面是全新的......

我有一个简单的应用程序,它正在呈现一些类别,数据在一个带有数组的对象的 js 文件中:

export default tabs = {
    categories: [
        { id: 'sample', title: 'sample' },
        { id: 'sample2', title: 'sample2' },
    ],
    deals: [
        { id: 'sample', title: 'sample' },
        { id: 'sample2', title: 'sample2' },
    ],
};

我想使用同一个文件来连接 API 并获取数据。

我尝试了很多类似的东西:

import React from 'react';
const APIcategories = '......';
export default {
    componentDidMount() {
        console.log('inside... ');
        fetch(APIcategories)
            .then((res) => res.json())
            .then((json) => this.setState({ data: json }));
    },
};

它只是从来没有在日志中得到任何东西......尝试了许多其他方法没有......

任何人都有类似的东西

提前欣赏!

到目前为止我没有错误地管理:

import React, { Component } from 'react';

const APIcategories = 'https://.......';

class SomeClass extends Component {
    constructor(props) {
        super(props);
        this.state = {
            data: [],
            error: null,
        };
        this.arrayholder = [];
    }
    componentDidMount() {
        this.someGetRequest();
    }
    someGetRequest = () => {
        console.log('inside------');
        fetch(APIcategories)
            .then((res) => res.json())
            .then((json) =>
                this.setState({ data: res.results, error: res.error || null })
            );

        this.arrayholder = res.results;
        console.log(arrayholder);
    };
}
console.log('File opened---------');
export default SomeClass;

标签: react-nativefetch

解决方案


创建一个类,然后实际使用它的方法..

class SomeClass extends Component {
  constructor(props) {
    super(props);

    this.state = {
      loading: false,
      data: [],
      error: null,
    };

    this.arrayholder = [];
  }

  componentDidMount() {
    this.someGetRequest();
  }

  someGetRequest = () => {
    const url = `https:...`;
    this.setState({ loading: true });

    fetch(url)
      .then(res => res.json())
      .then(res => {
        this.setState({
          data: res.results,
          error: res.error || null,
          loading: false,
        });
        this.arrayholder = res.results;
        console.log(res.results)
      })
      .catch(error => {
        this.setState({ error, loading: false });

      });
  };

 export default SomeClass;

此代码已使用 expo-cli 3.18.4 进行了测试


推荐阅读