Javascript React中的空状态,调用异步函数
为什么我的状态是空的Javascript React中的空状态,调用异步函数,javascript,reactjs,asynchronous,Javascript,Reactjs,Asynchronous,为什么我的状态是空的 类扩展组件{ 状态={ 电话号码:“, }; componentDidMount(){ const{options,wpApi}=this.props; getImageUrl(options.main\u img).then((res)=>{ this.setState({phoneImg:res}); }); log(“选项----”,选项); } render(){ const{options,wpApi}=this.props; const{phoneImg}=
类扩展组件{
状态={
电话号码:“,
};
componentDidMount(){
const{options,wpApi}=this.props;
getImageUrl(options.main\u img).then((res)=>{
this.setState({phoneImg:res});
});
log(“选项----”,选项);
}
render(){
const{options,wpApi}=this.props;
const{phoneImg}=this.state;
console.log(phoneImg);
还一些
}
}
您需要了解生命周期
componentDidMount
将在render
方法之后运行。
根据图表,(1)将在(2)之前运行
有关
注意:不要担心第一次的渲染
,当API完成->状态更改->渲染()将再次运行时就可以了。componentDidMount
的目的是。
import React,{Component}来自“React”;
导出默认类应用程序扩展组件{
建造师(道具){
超级(道具);
此.state={
phoneImg:“
};
}
componentDidMount(){
const{options,wpApi}=this.props;
这个。_getData()。然后((res)=>{
console.log(“2毫秒后等待”);
this.setState({phoneImg:res});
});
}
_getData(){
返回新承诺((解决)=>
setTimeout(()=>解析(“您的数据”),2000)
);
}
render(){
const{options,wpApi}=this.props;
const{phoneImg}=this.state;
console.log(phoneImg);
还一些;
}
}
输出
componentDidMount
在初始渲染后执行。由于this.state.phoneImg
的初始值为空字符串,因此在初始渲染期间,将记录空字符串。当componentDidMount
执行并更新状态时,组件将重新呈现。因此,phoneImg
的更新值将被记录。请编辑问题并使用文本将代码输入其中?使用图像是没有帮助的。当你说它是空的,你是指一个空字符串,还是未定义的?好的,我在这里要用什么?如果要在此处调用componentDidUpdate()?其中最好调用wpApi.getImageUrl(options.main_img).then((res)=>{this.setState({phoneImg:res});});它不应该是this.state,这是一个类字段。谢谢。我已经更新了答案,请看一下@jonrsharpeso,我必须在构造函数中这样做吗?是的,你可以这样做来加载数据。但是,当运行componentDidMount
时,状态已更改,然后render
函数将再次运行。@plaglamist将其移动到构造函数将没有帮助(并可能导致其他问题)因为它仍然是异步的-您的代码需要容忍这样一个事实,即在实际数据加载之前,phoneImg
将是一个空字符串。
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>
}
}
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>;
}
}