【问题标题】:setState in reactjs inside success function not setting state成功函数内的reactjs中的setState未设置状态
【发布时间】:2017-06-29 13:10:26
【问题描述】:

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

【问题讨论】:

  • 它的绑定问题这样写:success: (cl) =&gt; {this.setState({....}) 它应该可以工作。
  • 感谢您的评论,我不知道,但这也不起作用。

标签: reactjs parse-platform


【解决方案1】:

这是因为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") })           
},

【讨论】:

  • @user109640 很高兴能为您提供帮助。不要忘记在构造函数中移动你的this.state = {}
  • 构造函数中的状态不是必须的,使用最新的babel插件,即使没有构造函数也可以指定状态
  • @loelsonk 是的,我已经宣布了该州。再次感谢你。 Shubham 也谢谢你
  • @loelsonk 对我来说,change(obj) 方法在成功函数回调后没有被调用
猜你喜欢
  • 2019-12-30
  • 2020-01-15
  • 2022-07-27
  • 2019-04-04
  • 1970-01-01
  • 2017-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多