reactjs - setState() 导致状态变量未定义
问题描述
在大多数情况下,我遵循本教程。
我的 Django API 设置得很好。我有这个服务功能:
export default class GoalService{
getGoals() {
const url = `${API_URL}/api/goals`;
return axios.get(url).then(response => response.data);
}
}
componentDidMount
由my中的方法调用GoalList
:
class GoalTable extends Component {
constructor(props) {
super(props);
this.state = {
goals: [],
now: now.getDate(),
}
}
componentDidMount() {
var self = this;
goalService.getGoals().then(function (result) {
console.log(result);
self.setState({ goals: result.data })
});
}
render() { ... }
(这是上述链接教程的第 8 步)。
现在,当我尝试使用时{ this.state.goals.map(...) }
,我得到了错误TypeError: this.state.goals is undefined
。看看其他线程,很多人似乎都遇到过这个问题——但它的出现是因为他们在发出的请求setState()
之外setState()
使用过,而且由于是异步的,所以状态被设置为空白。我在对 的调用中使用它then
,所以我认为这不是问题。
我尝试添加第二个参数then
(以防此操作不成功),但是,getGoals()
调用成功,并成功打印出 Django API 发回的 JSON。同样,我可以在开发人员工具的“网络”选项卡中看到请求按预期进行。
这里可能出了什么问题?为什么状态没有正确更新返回的 JSON?
解决方案
正如评论中提到的,教程有一个错字,这意味着代码尝试访问response.data.data
而不是response.data
.
解决方法是删除对对象的这种额外级别的钻取:
componentDidMount() {
var self = this;
goalService.getGoals().then(function (result) {
self.setState({ goals: result }) // no .data
});
}
另外,请注意,您可以通过使用箭头函数(自动this
从定义它们的位置绑定 )和对象初始化简写来简化此代码:
componentDidMount() {
// { goals } is the same as { goals: goals }
goalService.getGoals().then(goals => this.setState({ goals }));
}
推荐阅读
- python - FLASK:从 python dict 在 JINJA 中创建表
- sql - 使用 SQL 从表中的 xml 中提取节点值
- html - 如何让我的网站在移动设备上看起来更好?
- java - 更改 Spring Boot 外部化配置时的向后兼容性
- process - Camunda同步流程实例不会挂起
- c# - 替换二进制文件中的某些内容而不完全加载或重写它
- openstreetmap - 定义一个特定位置以从中提取“住宅”数据
- vue.js - Vuetify.js 页面多分页
- apache-spark - 列的累计和
- asp.net-core - 在 _Layout ASP.NET 3.0 Razor Pages 项目中包括注销功能