绑定(这)不是工作在阿贾克斯成功功能 [英] bind(this) not working on ajax success function

查看:226
本文介绍了绑定(这)不是工作在阿贾克斯成功功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用的反应和jQuery。这里是我的code的一部分。

I use react and jQuery. here's a part of my code.

在反应成分坐骑,我执行Ajax请求,知道用户登录。

Before react component mounts, I perform ajax request to know if user is logged in.

它应该设置状态时的响应返回状态code 200
我会不正确地使用绑定(本)

It is supposed to set state when a response returns status code 200.
am I incorrectly using 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(本); 成功(函数(响应){...})回调。

是下面的。

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


解决方案
我的code以上是反模式。
按照由答案我建议采用的方法之一。 另外,已经作出反应提供了非常有用的解决方案对我的情况的文档:通过AJAX加载初始数据


Solutions
My code above was antipattern.
Follow one of the methods suggested by Answer i adopted. Plus, React documentation already provided very useful solution about my case: Load Initial Data via AJAX

此外,的setState是异步的。
这就是为什么我想,当我登录它在控制台上的setState不能正常工作。
毕竟,我查里呈现,并通过为道具,以子组件。

Also, setState is asynchronous.
That's why I thought setState not working when I log it on console.
After all, i checked inside render and pass as props to child components.

推荐答案

我觉得你不应该使用Ajax调用了的setState在componentWillMount; 这样做在componentDidMount

I think you shouldn't use an ajax call for setState in componentWillMount; do it in componentDidMount.

如果你不想做的第一渲染您在数据的之前这些数据只是用于初始化执行外,并成功您的电话与所获取的数据渲染视图== ===>      然后把它放在 getInitialeState

If you don't want to do the first render before you're having data AND those data are just for initialization perform your call outside and on success render your view with the fetched data =====> and then put it in getInitialeState

阅读这个,如果你选择这条路(事业为在doc说这是不是在一定条件下的反模式)的https://facebook.github.io/react/tips/props-in-getInitialState-as-anti-pattern.html

Read this if you choose this path (cause as stated in the doc this is not an anti-pattern on certain conditions): https://facebook.github.io/react/tips/props-in-getInitialState-as-anti-pattern.html

希望它能帮助

编辑: 有双向做第一个,你获取的外反应类

There is two way to do it the first one you fetch outside your react class

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

和在MyView的从道具数据getInitialeState。 使用此方法仅当您需要打电话给你的get一次(读反模式的东西)。

and in MyView you getInitialeState from props "data". Use this method only if you need to call your get once (read the anti-pattern stuff).

另一种方法是做你正在做什么,但在componentDidMount。 https://facebook.github.io/react/tips/initial-ajax.html

Other method is doing what you are doing but in componentDidMount. https://facebook.github.io/react/tips/initial-ajax.html

希望它更清晰。

这篇关于绑定(这)不是工作在阿贾克斯成功功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆