我使用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
当我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 不起作用的原因。
毕竟,我在渲染内部检查并作为props传递给子组件。