javascript - 在登录部分工作时无法在未安装的组件中调用 setState

标签 javascript reactjs

我正在开发 Facebook 的登录功能,我在我的控制台中看到了这个问题。它说:

Can't call setState (or forceUpdate) on an unmounted component. 
This is a no-op, but it indicates a memory leak in your application.     
To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.

我得到 userProfile 的控制台日志,我们在其中看到来自 Facebook 的响应,之后代码的执行停止。因此,我没有看到我的登录被调度,setState 应该发生。

这是登录代码,我们只在一个部分执行setState

class SocialLogin extends Component{
  constructor(props){
    super(props);
    this.state={
        userData:""
    };
  }

componentDidMount() {
    (function (d, s, id) {
        var js, fjs = d.getElementsByTagName(s)[0];
        console.log("d",d);
        console.log("s",s);
        console.log("id",id);
        debugger
        if (d.getElementById(id)) {
            return;
        }
        js = d.createElement(s);
        console.log("js",js);
        js.id = id;
        js.src = "https://connect.facebook.net/en_US/sdk.js";
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));


    window.fbAsyncInit = ()=> {
        window.FB.init({
            appId: FACEBOOK_APP_ID,//Change with your Facebook app id
            autoLogAppEvents: true,
            xfbml: true,
            version: 'v3.0'
        });

        window.FB.Event.subscribe('auth.statusChange', response => {
             console.log("event",response);
             debugger
            if (response.authResponse) {
                this.checkLoginState();
            } else {
                console.log('[FacebookLoginButton] User cancelled login or did not fully authorize.');
            }
        });
    };
}
// componentDidUpdate(){
//     console.log("updateduserprofile",userProfile);
//     this.props.loginUser(userProfile);
//     debugger
//    //window.location.href="https://rooter-web-app-dev.firebaseapp.com/home/cricket"
// }

checkLoginState(){
    debugger
    window.FB.getLoginStatus(function(response) {
        console.log("response inside checklogin",response);
        this.statusChangeCallback(response);
    }.bind(this));
}

login(){
    window.FB.login(this.checkLoginState(), {scope: 'email'});
}

statusChangeCallback(response) {
    console.log("response",response);
    accessToken =response && response.authResponse && response.authResponse.accessToken;

    if (response.status === 'connected') {
        this.testAPI();

    } else if (response.status === 'not_authorized') {
        console.log("[FacebookLoginButton] Person is logged into Facebook but not your app");
    } else {
        console.log("[FacebookLoginButton] Person is not logged into Facebook");
    }
}

testAPI() {

    window.FB.api('/me' ,(response)=> {
        console.log("testAPI",response);

       if(response){
           userProfile = {
                  auth:accessToken,
                  id:response.id,
                  name:response.name,
                  provider: "Facebook",

                };
                console.log("userProfile",userProfile);
                this.setData(userProfile);
       }

        console.log('[FacebookLoginButton] Successful login for: ', response);
    });

}
setData=(userProfile)=>{
    this.setState({
        userData:userProfile
    },()=>{
        console.log('inside setData');
        if(userProfile!==undefined){
            console.log("inside callback",userProfile);
            this.props.loginUser(this.state.userData);
        }

    });
}

render(){
    return (
        <div style={loginstyle}>
        <button onClick={()=>this.login() }  className="loginBtn loginBtn--facebook">
          Login with Facebook
         </button>

       </div>
    )
}                                                                                                                                                                                                                                     z

最佳答案

在更新组件状态之前,您需要检查它是否已安装??如果未安装则不要更新到它的状态,为此你需要维护指示组件安装状态的标志 考虑以下代码

constructor(props){
   super(props);
   this.state={
      userData:""
   };
  //initially its false
   this.mount=false
 }
componentWillUnMount(){
    //make it false here
    this.mount=false;
}
componentDidMount() {
//make it true when mounted
    this.mount=true;
}

现在在使用 setState 之前确保 this.mount 是 true,希望它会有所帮助!

关于javascript - 在登录部分工作时无法在未安装的组件中调用 setState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55724188/

相关文章:

javascript - 使用 javascript 插入 XML 源以进行选择

javascript - 单击淡出 ul 的 anchor 标记上的事件?

javascript - 如何在 React 应用程序中使用 Fetch 向 Flask API 发送 POST 请求

javascript - react native : How to switch page without using NavigatorIOS component?

javascript - 在 jQuery 中从父元素外部单击 "this"时如何切换子元素?

javascript - jQuery 对图像的悬停效果

javascript - 关闭Javascript

javascript - 在 map 功能中传递 Prop 不起作用。将其作为 key 传递

node.js - 构建 React 项目时出现错误 : node_modules\react-native-fs\FS. common.js : Unexpected token, 预期 ","(30:29)

.net - 如何制作 React App windows 身份验证