首页 > 解决方案 > ReactJS 无法访问 setState 中的响应对象

问题描述

我正在尝试将 setSet 作为我的 RestAPI 输出的一部分进行更新。但是我收到一个错误,即响应对象未定义。我能够在setState方法之外记录它。

代码

addNewTodo = () => {
axios.post('http://localhost:5001/todos', "task="+this.state.newTodoList.task)
      .then(response=>console.log(response.data))
      .then(response=>{
              this.setState(prevState=>({
                  TodoList: prevState.TodoList.push(response.data),
              }))
            });
{this.toggleNewTodoModal()}
}

我在错误之前登录控制台

{任务:“ddd”,id:“todo10”}

错误:

TypeError:无法读取未定义的属性“数据”

在下一行

TodoList: prevState.TodoList.push(response.data),

标签: reactjs

解决方案


因此,您的第一个.then返回控制台日志,这意味着您的第二个.then将不再具有任何值。如果您将代码更改为此:

关于将新数据推送到反应状态数组,在以后的 React 版本中推荐的方法是在修改状态时使用更新器函数来防止竞争条件。所以将新数据推送到状态数组应该如下所示

axios
    .post('http://localhost:5001/todos', 'task=' + this.state.newTodoList.task)
    .then(response => {
        console.log(response.data);
        this.setState(prevState => ({
            TodoList: [...prevState.TodoList, response.data],
        }));
    });

它应该工作得很好。.then只要您返回一些值而不是控制台日志,您就可以尽可能多地链接,例如,在fetch

fetch('some_url', {
  method: 'GET',
})
.then(res => res.json()) // this returns the data 
.then(data => console.log(data)) // this has access to the data

推荐阅读