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

bind(this) not working on ajax success function

本文关键字:成功 函数 不起作用 ajax this Bind      更新时间:2023-09-26

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

在react组件挂载之前,我执行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

当我在success(function(response){...})回调中执行console.log(this);

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

<

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

setState也是异步的。
这就是为什么我认为setState不工作,当我登录控制台。
毕竟,我检查了内部渲染并将其作为道具传递给子组件。

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

如果你不想做第一次渲染之前,你有数据这些数据只是用于初始化执行调用外部和成功渲染你的视图与获取的数据=====>

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

如果你选择了这个路径,请阅读下面的内容(正如文档中所述,这在某些情况下不是反模式):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中你从props "data"中获取initialstate。只有当你需要调用get一次时才使用这个方法(阅读反模式的内容)。

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

希望能更清楚