首页 > 解决方案 > React 中的空状态,异步函数的调用

问题描述

为什么我的状态是空的?

我只是做了简单的反应,我在这里错过了什么?

在此处输入图像描述

class HeroOlive extends Component {
  state = {
    phoneImg: "",
  };
  componentDidMount() {
    const { options, wpApi } = this.props;

    wpApi.getImageUrl(options.main_img).then((res) => {
      this.setState({ phoneImg: res });
    });
    console.log("OPTIONS ---- ", options);
  }
  render() {
    const { options, wpApi } = this.props;
    const { phoneImg } = this.state;
    console.log(phoneImg);
return <h1>some</h1>
}
}

标签: javascriptreactjsasynchronous

解决方案


你需要了解life cycle

componentDidMount将在render方法之后运行。 在此处输入图像描述

根据图表,(1)将在(2)之前运行。

关于React 生命周期方法图的有用链接

注意:不要担心第一个render,API 完成后就可以了 -> 状态更改 -> render() 将再次运行。的目的componentDidMount 就是这样。

演示在这里:

import React, { Component } from "react";

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

  componentDidMount() {
    const { options, wpApi } = this.props;
    this._getData().then((res) => {
      console.log("Waiting after 2ms ");
      this.setState({ phoneImg: res });
    });
  }

  _getData() {
    return new Promise((resolve) =>
      setTimeout(() => resolve("Your data"), 2000)
    );
  }

  render() {
    const { options, wpApi } = this.props;
    const { phoneImg } = this.state;
    console.log(phoneImg);
    return <h1>some</h1>;
  }
}

输出 在此处输入图像描述


推荐阅读