Javascript React JS TypeError:无法读取属性';设置状态';未定义的
如果我试图在函数中调用setState(编辑或保存),我会得到“TypeError:无法读取未定义的属性'setState'。 如果我声明一个arrow函数,它会工作,但我不明白为什么Javascript React JS TypeError:无法读取属性';设置状态';未定义的,javascript,reactjs,Javascript,Reactjs,如果我试图在函数中调用setState(编辑或保存),我会得到“TypeError:无法读取未定义的属性'setState'。 如果我声明一个arrow函数,它会工作,但我不明白为什么 import React, { Component } from 'react'; class Note extends Component { constructor(props) { super(props); this.state = { e
import React, { Component } from 'react';
class Note extends Component {
constructor(props) {
super(props);
this.state = {
editing: false
}
}
edit (){
this.setState({ editing: true })
}
save() {
this.setState({ editing: false })
}
renderEditNote() {
return (
<div className="note">
<textarea></textarea>
<button onClick={this.save}>SAVE</button>
</div>
)
}
renderDisplayNote() {
return (
<div className="note">
<p>{this.props.children}</p>
<span>
<button onClick={this.edit}>Edit</button>
<button onClick={this.remove}>X</button>
</span>
</div>
)
}
render() {
return this.state.editing ? this.renderEditNote() : this.renderDisplayNote()
}
}
export default Note
import React,{Component}来自'React';
类注释扩展了组件{
建造师(道具){
超级(道具);
此.state={
编辑:假
}
}
编辑(){
this.setState({editing:true})
}
保存(){
this.setState({editing:false})
}
renderitnote(){
返回(
拯救
)
}
renderDisplayNote(){
返回(
{this.props.children}
编辑
X
)
}
render(){
返回this.state.editing?this.renderditnote():this.renderdisplaytnote()
}
}
导出默认注释
要让它工作,你应该
this.save.bind(this)
this.edit.bind(this)
this.remove.bind(this)
您尚未绑定它,因此方法edit()、save()和remove()中的this不是Note类。
您可以在这些方法中使用console.log(这个)来理解为什么要使它工作,您应该这样做
this.save.bind(this)
this.edit.bind(this)
this.remove.bind(this)
您尚未绑定它,因此方法edit()、save()和remove()中的this不是Note类。
您可以在这些方法中执行console.log(this)来理解为什么您需要对编辑和保存功能执行此操作,这样当单击返回时它就不会丢失
例如:
<button onClick={this.edit.bind(this)}>Edit</button>
编辑
或者您也可以在构造函数中执行此操作,如下所示:
this.edit=this.edit.bind(this)
您需要此
用于编辑
和保存
功能,以便在单击返回时不会丢失
例如:
<button onClick={this.edit.bind(this)}>Edit</button>
编辑
或者您也可以在构造函数中执行此操作,如下所示:
this.edit=this.edit.bind(this)
您确定设置了此
吗?此
的值取决于函数的调用方式。另请参见感谢您提供的链接,它为我带来了清晰的信息您确定设置了此
吗?此
的值取决于函数的调用方式。谢谢你的链接,它给我带来了清晰。非常感谢你,以这种方式工作。非常感谢,以这种方式工作。