【发布时间】:2017-04-23 21:21:39
【问题描述】:
在 ReactJS 中做一件简单的事情时,我收到一个错误“TypeError: Cannot read property 'setState' of undefined”。我正在尝试使用 axios 用响应数据填充输入。到目前为止没有成功。 我对 axios 和 ReactJs 都很陌生,所以我可能忽略了一些非常简单的事情?
我希望“响应文本”在 TypeError 修复后显示在表单的输入字段中。
这是我的组件:
class BasicInfoBlock extends React.Component {
constructor(props) {
super(props);
this.state = { name : "EventTestName" };
}
componentDidMount() {
axios
.get(getBaseUrl()+`get`)
.then(function (response) {
this.setState({name: "RESPONSE TEXT"});
//this.setState({name: response.data.name});
})
.catch((e) =>
{
console.error(e);
});
//this.setState({});
}
render(){
return(
<form className="form-horizontal">
<div className="form-group">
<label htmlFor="eventName" className="col-sm-2 control-label">Name</label>
<div className="col-sm-10">
<input type="text" id="eventName" className="form-control" placeholder="Event name" defaultValue={this.state.name}/>
</div>
</div>
</form>
);
}
}
感谢您的帮助
编辑:这不是一个重复的问题,这个问题与“this”在回调中不可用有关。选择为重复的问题与绑定有关。
【问题讨论】:
-
问题在于回调函数内部
this的上下文。 -
不是重复的,阅读编辑
-
它与
this在另一个函数中丢失上下文的根本问题相同。绑定是一种解决方案,箭头是另一种解决方案,使用像var self = this;这样的单独变量,然后调用self.setState是另一种解决方案。
标签: javascript reactjs axios