在寫react mobx的demo時鹊汛,給checkbox
添加一個onChange
事件蒲赂,并且忘記在constructor
中bind
事件,導(dǎo)致this
指向錯誤
import React from 'react'
import { observer } from 'mobx-react'
@observer
class Todo extends React.Component {
constructor(props){
super(props);
// this.toggleFinished = this.toggleFinished.bind(this)
// this.removeTodo = this.removeTodo.bind(this)
}
toggleFinished() {
console.log(this) // undefined刁憋,因?yàn)椴]有綁定this
const todo = this.props.todo;
todo.finished = !todo.finished
}
removeTodo = () => {
const i = this.props.i;
// const AppState = this.props.AppState;
this.props.AppState.todoList.splice(i,1)
}
render(){
const todo = this.props.todo;
return (
<li>
<input type="checkbox" checked={todo.finished} onChange={this.toggleFinished} />
id:{todo.id},task:{todo.task},finished:{todo.finished?'true':'false'}
<button onClick={this.removeTodo}>remove it</button>
</li>
)
}
}
export default Todo
image.png
報錯原因: this
并沒有綁定到Todo
上
官方文檔React處理事件中這么解釋:在JSX回調(diào)中你必須注意 this
的指向滥嘴。 在 JavaScript 中,類方法默認(rèn)沒有 綁定 的至耻。如果你忘記綁定 this.handleClick
并將其傳遞給onClick
若皱,那么在直接調(diào)用該函數(shù)時,this
會是 undefined
尘颓。
解決方法:
1.在constructor中綁定this
constructor(props){
super(props);
this.toggleFinished = this.toggleFinished.bind(this) // 將this綁定到當(dāng)前對象
// this.removeTodo = this.removeTodo.bind(this)
}
2.使用箭頭函數(shù) ()=>
toggleFinished =() =>{
console.log(this) // Todo...
// const todo = this.props.todo;
// todo.finished = !todo.finished
}
箭頭函數(shù)()
this
指向
MDN解釋:在箭頭函數(shù)中是尖,this
與封閉詞法上下文的this
保持一致。在全局代碼中泥耀,它將被設(shè)置為全局對象饺汹。
在本章中,也就是this
指向外層調(diào)用者 Todo