setstate无法从res.data传递信息



当我这样运行代码时,控制台显示一个空数组。但是,当我使用console.log(res.data)时,我会发现员工的预期json对象没有问题。

  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));
};

无论哪种方式,代码是运行的,我还会获得一个未介绍的SyntaxError:JSON INPUT的意外结束,json.parse()错误消息。

     .then (console.log(this.state.userList))

console.log,记录当前状态(甚至在异步开始启动之前),console.log返回未定义,整个事物都评估为

 .then(undefined)

而是将函数传递到 .then,例如

.then(() => {
  console.log(this.state);
});

但是,作为setState也是异步的,这不会可靠地起作用。因此,您应该使用一个可以通过的回调,以便您在执行异步操作并更新状态后登录:

this.setState(
  { userList: res.data, firstName: "", lastName: "", position: "" },
  () => console.log("done", this.state)
)

setState是不同步的,因此您不能保证在使用 console.log

检查时更新状态值

async/await to recue

state = {
  userList: [],
  firstName: "",
  lastName: "",
  position: ""
};
loadUsers = async () => {
  const response = await API.getUsers();
  this.setState({
    ...state,
    userList: response.data, 
  }, () => console.log('[user list]', this.state.userList)
};

update

添加了差异语法

相关内容

最新更新