从 API 获取数据后如何更改状态?

时间:2021-07-26 02:45:53

标签: reactjs api get render setstate

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() 函数不会改变状态。获取数据后我应该如何改变状态?

2 个答案:

答案 0 :(得分:0)

你应该使用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;

答案 1 :(得分:0)

如果您使用“async”和“await”,则不必使用 then() 函数 你可以写

const data = await axios.get("url")
console.log(data.data)
this.setState({message:data.data})
相关问题