bind(this)不能在ajax成功函数上工作

seo*_*han 6 javascript ajax jquery reactjs

我使用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);
}
Run Code Online (Sandbox Code Playgroud)

编辑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
Run Code Online (Sandbox Code Playgroud)

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

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

Fra*_*ard 5

我认为你不应该在 componentWillMount 中对 setState 使用 Ajax 调用;在 componentDidMount 中进行

如果你不想做的第一渲染您在数据之前这些数据只是用于初始化执行您的通话外,并成功使您的观点与获取的数据=====>

<Myview data={initialDataFromTheCallSuccess} /> and then put it in getInitialState
Run Code Online (Sandbox Code Playgroud)

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

希望能帮助到你

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

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

在 MyView 中,您从道具“数据”中获取了InitialState。仅当您需要调用一次 get 时才使用此方法(阅读反模式内容)。

其他方法正在做你正在做的事情,但在 componentDidMount 中。 https://facebook.github.io/react/tips/initial-ajax.html

希望它更清楚