2017-03-25 26 views
1

我的小todo應用程序存在問題。每次我試圖刪除一個項目有一個錯誤Cannot read property 'todos' of undefined「這個」在我的類中是undefined

爲什麼this在裏面addTodo約束,但不removeTodo

觸發都是在這裏完成:<button onClick={() => removeTodo(id)}> X </button>

演示上JSfiddle

感謝。

+0

[Arrow功能VS函數聲明/表達式的可能的複製? ](http://stackoverflow.com/questions/34361379/arrow-function-vs-function-declaration-expressions-are-they-equivalent-exch) – Andreas

回答

0

您可以將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); 
} 
+1

謝謝你現在正在工作。我只是將'''action.bound()'''添加到我的函數中,並且所有內容都按預期工作。 –

+0

@jonathandion太棒了! – Tholle

相關問題