api调用后this.state为null

时间:2019-12-10 20:04:07

标签: reactjs

在componentDidMount中调用函数后,我正在安慰状态,但是它以EMPTY String的形式提供数据。

import React, { Component } from "react";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: ""
    };
  }

  getData = () => {
    functionApiCall().then(res => {
      this.setState({
        data: res.data
      }); // Here the state is getting set
    })
  }

  componentDidMount() {
    this.getData();
    console.log(this.state.data); //Empty string
  }

  render() {
    return <></>;
  }
}

export default App;

任何帮助将不胜感激。谢谢

2 个答案:

答案 0 :(得分:0)

好吧,我认为api调用返回的是null,也许可以这样更改

  getData = () => {
      functionApiCall().then(res => {
      if(res && res.data) {
      this.setState({
        data: res.data
      })// Here the state is getting set
     } 
    }
  }

上面应该没问题,但以防万一尝试

 getData = () => {
        return new Promise(function(resolve, reject) {
          functionApiCall().then(res => {
          if(res && res.data) {
          this.setState({
            data: res.data
          }, () => { resolve(res.data) })// Here the state is getting set
         } 
        } });
      }

并且componentDidMount等待您的诺言,该诺言在设置状态后就会解决

 async componentDidMount(){
        await this.getData();
        console.log(this.state.data) //NULL
      }

答案 1 :(得分:0)

setState是异步的,因此您无法立即访问它。

您可以像这样有条件地渲染:

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: null
    };
  }

  getData = () => {
    functionApiCall().then(res => {
      this.setState({
        data: res.data
      });
    });
  };

  componentDidMount() {
    this.getData();
  }

  render() {
    if (!this.state.data) {
      return <div>Loading...</div>;
    } else {
      return <div>Data: {JSON.stringify(this.state.data)}</div>;
    }
  }
}

export default App;

使用伪造的api示例codesandbox