首页 > 解决方案 > 从 API 获取数据后如何更改状态?

问题描述

constructor(props) {
        super(props);
        this.state = {
            message: ""
        };
    }

    async getData() {
        this.setState({...this.state})
        await axios.get("https://g...")
        .then(function(response) {
            console.log(response);
            this.setState({message: response.data})
        }).bind(this)
    }

    render() {
        return (
            <div>
                {this.state.message}
            </div>
        );
    }

我尝试使用此代码从 API 获取数据。但是,打印出来的消息只链接到原来的构造函数,getData()函数并没有改变状态。获取数据后我应该如何改变状态?

标签: reactjsapigetrendersetstate

解决方案


您应该使用componentDidMount,并将请求数据的函数放在 componentDidMount 生命周期中。

顺便说一句,您可以添加加载以增强用户体验:)

import React from 'react';

import "./styles.css";

const BASE_URL = 'https://api.github.com';

class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      message: ''
    }
  }

  componentDidMount() {
    this.getData();
  }

  async getData() {
    try {
      const result = await fetch(`${BASE_URL}/repos/facebook/react`);
      const toJson = await result.json();
      const stringify = JSON.stringify(toJson, null, 2);

      this.setState({
        message: stringify
      })
    } catch (error) {
      // ignore error.
    }
  }


  render() {
    const { message } = this.state;

    return (
      <div>
        {message}
      </div>
    )
  }
}

export default App;


推荐阅读