gpt4 book ai didi

javascript - bind(this) 不适用于 ajax 成功函数

转载 作者:数据小太阳 更新时间:2023-10-29 05:25:48 24 4
gpt4 key购买 nike

我使用 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

解决方案
我上面的代码是反模式的。
按照我采用的答案建议的方法之一进行操作。另外,React 文档已经为我的案例提供了非常有用的解决方案:Load Initial Data via AJAX

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

最佳答案

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

如果您不想在获得数据之前进行第一次渲染并且那些数据只是为了初始化在外部执行您的调用并在成功时使用获取的数据渲染您的 View == ===>

<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 中,您从 Prop “数据”中获取 InitialState。仅当您需要调用一次 get 时才使用此方法(阅读反模式内容)。

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

希望它更清晰

关于javascript - bind(this) 不适用于 ajax 成功函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31995180/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com