首页 > 解决方案 > this.state 在 api 调用后给出 null

问题描述

我在 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;

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

标签: reactjs

解决方案


好吧,我认为 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
      }

推荐阅读