在React Native中使用类和渲染api调用

问题描述 投票:0回答:1

我在React Native中完全陌生,我在从API调用渲染数据时遇到问题。当我在函数中执行此操作时,当我使用useEffect ...时它对我有用...但是在Class中,我不能使用它。

这里是我的代码示例...

export default class Categories extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            data: [],
            error: null,
        };
    }
    componentDidMount() {
        this.regionsGetRequest();
    }
    regionsGetRequest = () => {
        this.setState({ loading: true });

        const fetchData = async () => {
            const result = await axios(
                'https://...........json'
            );
            this.setState({
                data: result.data,
                error: result.error || null,
                loading: false,
            });

        };
        fetchData();
    };

    renderCategories = () => {
        const categoryLive = this.state.data;
        console.log(JSON.stringify(categoryLive));

[我进入控制台:未定义,未定义...,然后按应有的结果...由于某种原因它运行了3次...如果我尝试将其置于renderCategories之上:

componentDidMount() {
        renderCategories();
    }

我只得到一个未定义...当我连接变量categoryLive时,没有加载任何内容。

对不起,我一直在为此苦苦挣扎……任何帮助都非常感谢!!

react-native axios
1个回答
0
投票
export default class Categories extends React.Component {
  constructor(props) {
    super(props);

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

  }

  componentDidMount() {
    this.regionsGetRequest();
  }

  regionsGetRequest = () => {
    const url = `https://......`;
    //Please make sure it is https!
    this.setState({ loading: true });

    fetch(url)
      .then(res => res.json())
      .then(res => {
        this.setState({
          data: res.results,
          error: res.error || null,
          loading: false,
        });
        //Here your data is res.results as json, you can log it or process it..
        console.log(res.results)
      })
      .catch(error => {
        this.setState({ error, loading: false });
      });
  };
© www.soinside.com 2019 - 2024. All rights reserved.