reactjs - 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),
解决方案
因此,您的第一个.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
推荐阅读
- java - 使用文本数据保存表情符号时出现错误消息
- google-cloud-platform - 将 SQL 数据库转储(一个 SQL 文件中的多个表)导入 BigQuery
- python - 无法在选定元素上调用 click 方法
- r - 通过 sp_execute_external_script throws 执行 R 过程需要“ntext/nchar/nvarchar”类型的参数“@params”
- javascript - highstock xaxis.ordnial = true 不工作
- javascript - 基于 Alt 字符串的 DataTables 过滤
- django - vuejs - 没有提到任何节点
- ggplot2 - ggplot在一页中绘制多图
- javascript - JavaScript 全局执行上下文
- android - 从代码更改可绘制对象的颜色 (xamarin.android)