reactjs - reactjs中的setState在成功函数中不设置状态

标签 reactjs parse-platform

我使用 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/

相关文章:

javascript - 向 onKeyPress 函数添加参数

javascript - 通过fetch()向后端API发送POST请求时,body只有key没有value

ios - 在 Parse 上存储信息

ios - 通过 REST API 将图像保存到 Parse,然后在 iOS 应用程序中使用它

javascript - 为什么这个模拟 api 不能按预期工作?

javascript - Reactjs 中是否尊重多个 setState() 的顺序?

javascript - 如何在reactjs中使用条件渲染?

ios - findObjectsInBackgroundWithBlock 查询成功后返回 nil

ios - 解析 [PFInstallation currentInstallation] 返回 nil

ios - 从 Parse.com 中的指针检索 pfobject 数据的问题