簡體   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