2017-12-17 8 views
1

내가 반응 기본/REDUX/중포 기지로 로그인 프로세스를 만들려고 노력하고있어 나는 몇 가지 문제를 가지고 파견하지 onAuthStateChanged ... 원주민/돌아 오는/중포 기지 반응 -

내가 작업을 파견 onAuthStateChanged을 구현하려고 ,하지만 내가 원하는대로 작동하지 않습니다.

componentDidMount() { 
    firebaseAuth.onAuthStateChanged() 
     .then((user) => { 
      if (user) { 
       Actions.home(); 
      } else { 
       Actions.login(); 
      } 
     }); 
} 

2 - 나는 REDUX-썽크에 있지만 파견하지 않고 행동으로의 구현 : - 내가 직접 내 아래처럼 내 구성 요소에 onAuthStateChanged 구현할

1 : 그것은 두 가지 경우에 작동하고

(하지만 그 다음에 액션을 보내고 올바른 경로로 리디렉션)

export const isAuthenticated =() => { 
    firebaseAuth.onAuthStateChanged() 
     .then((user) => { 
      if (user) { 
       console.log("launch.action#isAuthenticated - user already connected"); 
      } else { 
       console.log("launch.action#isAuthenticated - user not connected"); 
      } 
     }); 

}};

그리고 내가하고 싶은 것은 이것이다 (하지만 작동하지 않습니다) :

export const isAuthenticated =() => { 
return (dispatch) => { 
    firebaseAuth.onAuthStateChanged() 
     .then((user) => { 
      console.log('user', user); 
      if (user) { 
       console.log("launch.action#isAuthenticated - user already connected"); 
       dispatch(isUserConnected(true)); 
      } else { 
       console.log("launch.action#isAuthenticated - user not connected"); 
       dispatch(isUserNotConnected(true)); 
      } 
     }); 
}; 

};

파견에 왜 효과가 없는지 누군가 설명 할 수 있습니까?

감사합니다.

+0

내에서 살고있는 내 loginRequest입니까? – Rbar

답변

1

두 가지 :

  1. 하나 개를 사용 기능 (isUserConnected, 예를 들면)과 값을 설정하는 중 true 또는 false (대신에 두 개의 서로 다른 기능 isUserNotConnectedisUserConnected를 사용하여, 당신은 현재로)

    firebase documentation

firebase.auth()-
  • 변경 firebaseAuth


    시도해보십시오.

    돌아 오는에

    (이것은 나를 위해 작동) (행동) :

    돌아 오는에
    // Firebase 
    import firebase from 'firebase'; 
    
    // Redux Function 
    export const testFirebaseInRedux =() => { 
        return (dispatch, getState) => { 
        firebase.auth().onAuthStateChanged(function (user) { 
         if (user) { 
         console.log("testFirebaseInRedux: logged in"); 
         dispatch(isUserConnected(true)); 
         } else { 
         console.log("testFirebaseInRedux: not logged in"); 
         dispatch(isUserConnected(false)); 
         } 
        }) 
        } 
    } 
    
    export const isUserConnected = (payloadToSet) => { 
        return { 
        type: 'IS_USER_CONNECTED', 
        payload: payloadToSet 
        } 
    } 
    

    (감속기) :

    export default function (state=initialState, action) { 
        switch(action.type) { 
        case 'IS_USER_CONNECTED': 
        return { 
         ...state, 
         isUserConnected: action.payload 
        } 
        default: 
        return { 
         ...state 
        } 
        } 
    } 
    

    구성 요소 :

    // Libraries 
    import React from 'react'; 
    
    // Redux 
    import {connect} from 'react-redux'; 
    import {bindActionCreators} from 'redux'; 
    import {testFirebaseInRedux} from './../actions/index.js'; 
    
    class YourComponent extends React.Component { 
        constructor(props) { 
        super(props); 
      } 
    
        componentDidMount() { 
        this.props.testFirebaseInRedux() 
        } 
    
    } 
    
    function mapStateToProps(state) { 
        return { 
         user: state.user 
        }; 
    } 
    
    function matchDispatchToProps(dispatch) { 
        return bindActionCreators({ 
         testFirebaseInRedux: testFirebaseInRedux, 
        }, dispatch) 
    } 
    
    
    export default connect(mapStateToProps, matchDispatchToProps)(YourComponent); 
    
  • +0

    내 firebaseAuth는 firebase.auth()입니다. 내가 가진 것은 정확하게 당신이 한 일입니다. 사실 그것은 반환 (파견) 물건을 사용할 때 onAuthStateChanged 응답 안에 들어 가지 않습니다 .../ – Bloumdsq

    0

    . 다음은 루트 컨테이너의 예제입니다. 가장 높은 구성 요소는 거의 같습니다.

    ** 귀하의 경우에는 authStateChangeListener를 componentDidMount() 내부와 같이 앱 레벨 구성 요소로 이동해야합니다. 그런 다음 사용자가 존재할 경우 우려를 분리하십시오. 그런 다음 상점 갱신을 표시하는 조치에서 함수를 호출하십시오.

    componentDidMount() { 
    // if redux persist is not active fire startup action 
    if (!ReduxPersist.active) { 
        this.props.startup() 
    } 
    
    // ********* Add a listener from the database to monitor whos logged in. ********* 
    firebase.auth().onAuthStateChanged((user) => { 
        // ********* If a user is logged in firebase will return the user object. THEY ARE NOT LOGGED IN THOUGH ********* 
        if (user) { 
        console.log('onAuthStateChanged', user) 
        // ********* Then we call an official Firebase login function through actions ********* 
        this.props.loginRequest(user); 
        } else { 
        console.log('No user signed in') 
        } 
    }); 
    
    // ********* After logging in the found user from above we need to set them to redux store ********* 
    let signedInUser = firebase.auth().currentUser; 
    
    if (signedInUser) { 
        this.props.loginRequest(signedInUser); 
        console.log('currentUserSignedIn', signedInUser) 
    } else { 
        console.log('no active user', signedInUser) 
    } 
    

    }

    는 그리고 이것은 당신이`isUserNotConnected`와`isUserConnected`의 기능을 공유 할 수 있습니다 내 행동

    export const loginRequest = user => dispatch => { 
        // ******** This gets called in RootContainer on mount, it will populate redux store with the entire User object from firebase ******** 
        // ******** FYI - The entire user object also contains their vehicles ******** 
        // ******** Here we need to check if user already exists in Firebase Database so that we dont overwrite their old data ******** 
        // ******** WARNING! With Firebase if you set data to a spot that has existing data it will overwrite it! ******** 
        console.log('RECIEVED USER TO LOOKUP', user); 
        firebase.database().ref('users/' + user.uid).once('value').then(function (snapshot) { 
         // ******** This method is straight from their docs ******** 
         // ******** It returns whatever is found at the path xxxxx/users/user.uid ******** 
         let username = snapshot.val(); 
         console.log(' FOUND THIS USER FROM THE DB', username); 
         { 
          // ******** If the username object is empty there wasn't any data at xxxxxx/user/user.uid ******** 
          // ******** It's safe to write data to this spot ******** 
          username === null ? firebase.database().ref('users/' + user.uid).set({ 
           account: username 
          }).then(function() { 
           console.log('STORED THIS USER TO FIREBASE DB', username); 
           dispatch(userSet(username)) 
          }) 
           // ******** Otherwise, the user already exists and we should update redux store with logged in user ******** 
           : dispatch(userSet(username)) 
         } 
        }) 
         .catch((err) => console.log(err)); 
    
        dispatch(userSet(user)) 
        console.log('INSIDE FIREBASEE DB SET', user) 
    
    }; 
    
    +0

    그래서 내 행동 내에서 onAuthStateChangedListener를 가질 수 없다고 생각합니까? 리니어는 구성 요소에서만 작동합니까? – Bloumdsq

    +0

    짧은 대답은 네가 행동에 넣을 수 있다는 것입니다. 하지만 여전히 앱 수준에서 호출해야합니다. 그래서 첫 번째 대답에서 그는 그렇게합니다. 내 기분 전환점을 확인하십시오. –

    +0

    방금 ​​앱에 기능을 추가 했으므로 모든 기능이 작동하지 않습니다. –