javascript - 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>
}
}
解决方案
你需要了解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>;
}
}
推荐阅读
- html - 如何在Angular 6模板中减去时间值
- c++ - sycl 内核调用很慢
- asynchronous - 重载广播,使其执行异步
- sed - 如何使用 sed 和变量名称,而不在 macOS 中添加尾随换行符?
- angular - 如何访问Angular中ngOnChanges上的@Input参数以外的变量?
- mysql - MySQL 查询检索两个类别中的标签(不是 OR)[WordPress 原始 SQL]
- flutter - Flutter video_player VideoProgressIndicator 擦洗在暂停时在 IOS 上不起作用
- html - Bootstrap 4 进度条在弹出框内不起作用(看起来像弹出框限制了 CSS 属性)
- c - 找到二维数组每一列的最大值
- r - 如何计算R中一列中的多个文本值?