gpt4 book ai didi

javascript - "this"在我的类(class)中未定义

转载 作者:行者123 更新时间:2023-11-28 04:49:49 24 4
gpt4 key购买 nike

我的小待办事项应用程序有问题。每次我尝试删除项目时都会出现错误 Cannot read property 'todos' of undefined

为什么this绑定(bind)在 addTodo 内但不是removeTodo

触发器在这里完成:<button onClick={() => removeTodo(id)}> X </button>

演示 JSfiddle

谢谢。

最佳答案

您可以将 removeTodo 制作为属性初始化箭头函数或使用 action.bound 装饰器。您还必须使用 MobX 数组 replace这样您就不会丢失引用:

removeTodo = (id) => {
var filtered = this.todos.filter(todo => todo.id !== id);
this.todos.replace(filtered);
}

或者:

@action.bound
removeTodo(id) {
var filtered = this.todos.filter(todo => todo.id !== id);
this.todos.replace(filtered);
}

关于javascript - "this"在我的类(class)中未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43018798/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com