javascript - this.setState is failing to pass information from res.data
问题描述
When I run my code like this, the console shows an empty array. However when I use console.log(res.data) I get the expected json object of employees without a problem.
state = {
userList: [],
firstName: "",
lastName: "",
position: ""
};
loadUsers = () => {
API.getUsers()
.then(res =>
this.setState({ userList: res.data, firstName: "", lastName: "",
position: "" })
)
.then (console.log(this.state.userList))
.catch(err => console.log(err));
};
Either way the code is run I also get an Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse () error message.
解决方案
.then (console.log(this.state.userList))
立即调用 console.log,记录当前状态(甚至在异步内容开始之前),console.log 返回 undefined 并且整个事情评估为
.then(undefined)
相反,将函数传递给.then
,例如
.then(() => {
console.log(this.state);
});
但是,由于 setState 也是异步的,因此无法可靠地工作。因此,您应该使用可以传递给 setState 的回调,以便在异步操作完成并更新状态后登录:
this.setState(
{ userList: res.data, firstName: "", lastName: "", position: "" },
() => console.log("done", this.state)
)
推荐阅读
- c - C中的意外位移行为
- c++ - 无需重载的类型和 const 类型的通用函数
- visual-studio-code - “ANY_NODE_APP”在 Windows 10 上不是内部或外部命令、可运行程序或批处理文件
- sql - 有没有办法使用 SQL 将字符串转换为列名?
- python - 进度条 - 类型错误:“模块”对象不可调用
- python - KeyError: 'mae' 绘制 Keras 模型训练进度时
- tensorflow - Tensorflow - 使用 GPU 时 CPU 使用率高
- geoserver - Geoserver 启动时间长
- c# - 运行代理场景时,“期望用双引号括起来的属性名称”
- r - 如何多次进行简单回归?