reactjs中的setState在成功函数中不设置状态
setState in reactjs inside success function not setting state
我使用 ParsePlatform 作为后端存储,使用 reactjs 作为前端。我可以使用 Parse.Query 获取解析数据,但无法使用返回值,因为我不知道如何设置成功获取结果的状态。我在 componentDidMount()
中这样尝试过
import React from 'react'
import Parse from 'parse'
class ConferenceInfo extends React.Component {
state={
someData:null
}
componentDidMount(){
this.getConferenceInfo()
}
getConferenceInfo(){
var ConferenceListing = Parse.Object.extend("ConferenceListing");
var cl = new Parse.Query(ConferenceListing);
cl.get("8glBIjeRrC", {
success: function(cl) {
// The object was retrieved successfully.
alert(cl.get("someData")) //it works
//this.setState({someData:cl.get("someData")}) not working
},
error: function(object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and message.
}
});
}
render() {
return (
<div>
{this.state.someData} //no result
</div>
)
}
}
export default ConferenceInfo
这是因为this
不在同一个范围内。您在 success
属性 中调用它,函数回调。
要使其正常工作,我们需要 bind
this
。
首先创建构造方法。
constructor(props) {
super(props);
// Our new bind method ref
this.change = this.change.bind(this);
}
然后添加新方法change
change(obj) {
this.setState(obj);
}
你的 success
回调终于来了
success: function(cl) {
// ...
this.change({ someData: cl.get("someData") })
},
我使用 ParsePlatform 作为后端存储,使用 reactjs 作为前端。我可以使用 Parse.Query 获取解析数据,但无法使用返回值,因为我不知道如何设置成功获取结果的状态。我在 componentDidMount()
中这样尝试过import React from 'react'
import Parse from 'parse'
class ConferenceInfo extends React.Component {
state={
someData:null
}
componentDidMount(){
this.getConferenceInfo()
}
getConferenceInfo(){
var ConferenceListing = Parse.Object.extend("ConferenceListing");
var cl = new Parse.Query(ConferenceListing);
cl.get("8glBIjeRrC", {
success: function(cl) {
// The object was retrieved successfully.
alert(cl.get("someData")) //it works
//this.setState({someData:cl.get("someData")}) not working
},
error: function(object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and message.
}
});
}
render() {
return (
<div>
{this.state.someData} //no result
</div>
)
}
}
export default ConferenceInfo
这是因为this
不在同一个范围内。您在 success
属性 中调用它,函数回调。
要使其正常工作,我们需要 bind
this
。
首先创建构造方法。
constructor(props) {
super(props);
// Our new bind method ref
this.change = this.change.bind(this);
}
然后添加新方法change
change(obj) {
this.setState(obj);
}
你的 success
回调终于来了
success: function(cl) {
// ...
this.change({ someData: cl.get("someData") })
},