首页 > 解决方案 > 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.

标签: javascriptreactjs

解决方案


     .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)
)

推荐阅读