reactjs - 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;
任何帮助将不胜感激。谢谢
解决方案
好吧,我认为 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
}
推荐阅读
- typescript - 在 knockout.js (TypeScript) 中更改 observable 但不通知订阅者
- c++ - 如何使用接口从 C++ 中的模板强制使用通用数据类型?
- flutter - 尝试在颤振中使用 MultipartRequest 上传文件时出现握手异常
- python - Pandas 组合多个特定的先前行
- c - 如何使用 Intel Advisor 分析我的并行 MPI 应用程序?
- docker - 将 VNC 与 Docker 一起使用
- multithreading - DbSet.Add(和其他非数据库操作)线程安全吗?
- reactjs - React 中父组件如何重置多个子组件
- python - 如何从更深目录中的文件导入模块?
- wordpress - 图像未填充宽度屏幕