3 回答
![?](http://img1.sycdn.imooc.com/54586453000163bd02200220-100-100.jpg)
TA贡献1852条经验 获得超7个赞
如果您在任何方法中使用this.state,请使用箭头函数或绑定您的操作。
箭头函数:
onSubmitUpdateState = (newNote) => {
const oldState = [...this.state.notes]
// Problem 2)
this.setState({notes: [...oldState, newNote]});
}
绑定方法: 创建构造函数并在构造函数中添加这一行
this.onSubmitUpdateState = this.onSubmitUpdateState.bind(this)
没有构造函数
<Create updateState={this.onSubmitUpdateState.bind(this)}/>
![?](http://img1.sycdn.imooc.com/545846070001a15002200220-100-100.jpg)
TA贡献1827条经验 获得超4个赞
在 Javascript 中,类方法在默认情况下不受限制,这个 SO 答案讨论了为什么会这样?
如果您不使用箭头函数,请确保bind()您的事件处理程序能够访问this.
<Create
updateState={this.onSubmitUpdateState.bind(this)} // pass a binded handler
/>
![?](http://img1.sycdn.imooc.com/545845d30001ee8a02200220-100-100.jpg)
TA贡献1784条经验 获得超8个赞
尝试这样做
class App extends Component{
state = {
notes: []
}
componentDidMount(){
fetch('http://localhost:3001/notes')
.then(resp => resp.json())
.then(data => this.setState({notes: data}))
}
onSubmitUpdateState = (newNote) => { //change to arrow function//
const oldState = [...this.state.notes]
// Problem 2)
this.setState({notes: [...oldState, newNote]});
}
render(){
return(
<div className="App">
<Notes notes={this.state.notes}/>
<Create updateState={this.onSubmitUpdateState}/>
</div>
)
}
}
export default App;
箭头语法this为您处理绑定。或者您可以bind在构造函数中使用该函数。`
基本上箭头函数this在调用时会保留上下文
添加回答
举报