我使用 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: function(cl) {
// ...
this.change({ someData: cl.get("someData") })
},
关于reactjs - reactjs中的setState在成功函数中不设置状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44826100/