绑定(this)不使用ajax成功函数

时间:2021-07-30 21:27:38

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

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

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

在react组件挂载之前,我执行ajax请求以确定用户是否已登录。

It is supposed to set state when a response returns status code 200.
am I incorrectly using bind(this)?

当响应返回状态码200时,它应该设置状态。我使用bind(这个)是否错误?

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);
}

Edit 01

编辑01

when I do console.log(this); in success(function(response){...}) callback.

当我做console.log(这个);在成功(函数(响应){…})的回调函数。

this was the below.

这是以下。

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

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

我上面的代码是反模式的。按照我所采用的回答所建议的方法。另外,React文档已经为我的案例提供了非常有用的解决方案:通过AJAX加载初始数据

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.

同时,设置状态是异步的。这就是为什么我认为在控制台登录时setState不起作用。毕竟,我检查了内部渲染和传递作为子组件的道具。

1 个解决方案

#1


4  

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

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

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 =====>

如果您不想在拥有数据之前进行第一次呈现,而这些数据只是用于初始化,那么请在外部执行调用,并在成功时使用fetchedredata =====>呈现视图

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

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

如果您选择此路径(如doc中所述,这在某些条件下不是反模式),请阅读本文:https://facebook.github.io/react/tips/props-in getinitialstate as anti-pattern.html

hope it helps

希望它能帮助

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

编辑:有两种方法可以做到这一点,第一种方法是在您的react类之外获取

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

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

在MyView中,你从道具“data”中获取getInitialState。只有在需要调用get一次(阅读反模式内容)时才使用此方法。

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

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

Hope it's clearer

希望它是清晰的

#1


4  

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

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

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 =====>

如果您不想在拥有数据之前进行第一次呈现,而这些数据只是用于初始化,那么请在外部执行调用,并在成功时使用fetchedredata =====>呈现视图

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

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

如果您选择此路径(如doc中所述,这在某些条件下不是反模式),请阅读本文:https://facebook.github.io/react/tips/props-in getinitialstate as anti-pattern.html

hope it helps

希望它能帮助

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

编辑:有两种方法可以做到这一点,第一种方法是在您的react类之外获取

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

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

在MyView中,你从道具“data”中获取getInitialState。只有在需要调用get一次(阅读反模式内容)时才使用此方法。

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

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

Hope it's clearer

希望它是清晰的