繁体   English   中英

bind(this)在ajax成功函数上不起作用

[英]bind(this) not working on ajax success function

我使用React和jQuery。 这是我的代码的一部分。

在安装组件之前,我执行ajax请求以了解用户是否已登录。

当响应返回状态码200时,应该设置状态。
我不正确地使用bind(this)吗?

componentWillMount: function(){
  $.ajax({
     url: "/is_signed_in",
     method: "GET",
     dataType: "json"
  }).success(function(response){
    this.setState({ signedIn: response.signed_in, currentUser: $.parseJSON(response.current_user) });
  }.bind(this));
},
componentDidMount: function(){
  console.log(this.state.signedIn);
}

编辑01

当我做console.log(this); success(function(response){...})回调中。

this是下面。

R…s.c…s.Constructor {props: Object, context: Object, state: Object, refs: Object, _reactInternalInstance: ReactCompositeComponentWrapper}_reactInternalInstance: ReactCompositeComponentWrapper_context: Object_currentElement: ReactElement_instance: ReactClass.createClass.Constructor_isOwnerNecessary: false_isTopLevel: false_mountImage: null_mountIndex: 0_mountOrder: 2_pendingCallbacks: null_pendingElement: null_pendingForceUpdate: false_pendingReplaceState: false_pendingStateQueue: null_renderedComponent: ReactCompositeComponentWrapper_rootNodeID: ".0"_warnedAboutRefsInRender: false__proto__: ReactCompositeComponentWrappercontext: Object__proto__: Object__defineGetter__: __defineGetter__()__defineSetter__: __defineSetter__()__lookupGetter__: __lookupGetter__()__lookupSetter__: __lookupSetter__()constructor: Object()hasOwnProperty: hasOwnProperty()isPrototypeOf: isPrototypeOf()propertyIsEnumerable: propertyIsEnumerable()toLocaleString: toLocaleString()toString: toString()valueOf: valueOf()get __proto__: get __proto__()set __proto__: set __proto__()getDOMNode: ()__reactBoundArguments: null__reactBoundContext: ReactClass.createClass.Constructor__reactBoundMethod: ()arguments: (...)bind: (newThis )caller: (...)length: 0name: ""__proto__: ()[[TargetFunction]]: ()[[BoundThis]]: ReactClass.createClass.Constructor[[BoundArgs]]: Array[0]props: Objectrefs: Object__proto__: ObjectrenderButtonSet: ()setSignedIn: ()__reactBoundArguments: null__reactBoundContext: ReactClass.createClass.Constructor__reactBoundMethod: setSignedIn(response)arguments: (...)caller: (...)length: 1name: "setSignedIn"prototype: setSignedIn__proto__: ()<function scope>arguments: (...)bind: (newThis )arguments: (...)caller: (...)length: 1name: ""prototype: boundMethod.bind__proto__: ()<function scope>caller: (...)length: 1name: ""__proto__: ()[[TargetFunction]]: setSignedIn(response)[[BoundThis]]: ReactClass.createClass.Constructor[[BoundArgs]]: Array[0]state: ObjectcurrentUser: Objectcreated_at: "2015-07-24T18:30:38.772+09:00"email: "admin@gmail.com"facebook_account_url: nullfirstName: "유찬"github_account_url: nullgoogleplus_account_url: nullid: 1lastName: "서"linkedin_account_url: nullsns_avatar: nulltwitter_account_url: nullupdated_at: "2015-08-14T02:14:21.091+09:00"__proto__: ObjectsignedIn: true__proto__: Object__proto__: ReactClassComponent

解决方案
我上面的代码是反模式。
请遵循答案我建议的一种方法。 另外,React文档已经为我的案例提供了非常有用的解决方案: 通过AJAX加载初始数据

同样,setState是异步的。
这就是为什么我在控制台上登录setState时认为它不起作用的原因。
毕竟,我检查了渲染内部,并将其作为道具传递给子组件。

我认为您不应该在componentWillMount中对setState使用Ajax调用; 在componentDidMount中完成

如果您不想在拥有数据之前进行第一次渲染,而这些数据仅用于初始化,请在外部进行调用,并在成功后使用获取的数据渲染视图=====>

<Myview data={initialDataFromTheCallSuccess} /> and then put it in getInitialState

如果您选择此路径,请阅读以下内容(由于doc中所述,在某些情况下这不是反模式): https : //facebook.github.io/react/tips/props-in-getInitialState-as-anti- pattern.html

希望能帮助到你

编辑:有两种方法可以做到,第一种方法是您在React类之外获取的

  $.ajax({...}).success(function(res) {
      <MyView data={res} /> // render your function on success
  });

在MyView中,您可以通过道具“数据”获取initialState。 仅当您需要调用一次get(请阅读反模式知识)时才使用此方法。

其他方法正在执行您正在执行的操作,但是在componentDidMount中。 https://facebook.github.io/react/tips/initial-ajax.html

希望更清楚

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM