Reactjs Firebase、react和redux等待存储更新
我有一个React应用程序连接到Firebase,我想检查用户是否在每次页面刷新时登录,并在操作中发送Reactjs Firebase、react和redux等待存储更新,reactjs,firebase,authentication,redux,redux-thunk,Reactjs,Firebase,Authentication,Redux,Redux Thunk,我有一个React应用程序连接到Firebase,我想检查用户是否在每次页面刷新时登录,并在操作中发送是否已签名,以下是操作创建者: export function checkAuth() { return dispatch => { firebaseAuth().onAuthStateChanged((user) => { if (user) { dispatch(signedInAction()) } else {
是否已签名,以下是操作创建者:
export function checkAuth() {
return dispatch => {
firebaseAuth().onAuthStateChanged((user) => {
if (user) {
dispatch(signedInAction())
} else {
dispatch(signedOutAction())
}
})
}
}
在减速器内部,我只需将布尔值isAuthenticated
设置为true/false:
case ActionTypes.isSignedIn: {
return Object.assign({}, state, {
isAuthenticated: true
})
}
case ActionTypes.isSignedOut: {
return Object.assign({}, state, {
isAuthenticated: false
})
}
因为我想在加载应用程序时检查用户是否已登录,所以我在componentDidMount
处发送操作(我猜这是错误的):
类主扩展组件{
建造师(道具){
超级(道具);
}
componentDidMount(){
store.dispatch(checkAuth());
}
render(){
返回(
);
}
}
这使得我检查isAuthenticated
的代码失败,因为它尚未在存储中设置,例如在Routes
组件中。解决这个问题的最好办法是什么?总而言之,我知道我可以使用条件渲染并检查何时定义了isAuthenticated
,但我不喜欢这种解决方案。思想?谢谢我已经完成了您尝试使用live应用程序并在其中使用Firebase Auth所做的工作。您只需将操作用作登录和注销,然后使用componentWillMount()和componentWillReceiveProps()检查用户是否登录:
行动:
import { auth } from '../fire';
export const GET_USER = 'get_user';
export function getUser(){
return dispatch => {
auth.onAuthStateChanged(user=>{
dispatch({
type: GET_USER,
payload: user
});
});
};
}
export function login(email,password){
return dispatch => auth.signInWithEmailAndPassword(email, password);
}
export function logout(){
return dispatch => auth.signOut();
}
export function createAccount(email, password){
return dispatch => auth.createUserWithEmailAndPassword(email, password);
}
您的减速器应具有以下功能:
import {GET_USER} from '../Actions/UserActions';
export default function( state = {loading:true}, action){
switch (action.type){
case GET_USER:
return { loading: false, ...action.payload };
default:
return state;
}
}
例如,在App.js中,刚开始时使用以下内容:
componentWillMount(){
this.props.getUser();
if(this.props.user.loading === false && this.props.user.email === undefined){
this.props.history.replace('/Login');
}
}
componentWillReceiveProps(nextProps){
if(nextProps.user.loading === false && nextProps.user.email === undefined){
this.props.history.replace('/Login');
}
}
这是因为您的道具中已经有您的身份验证凭据
我希望这对您有用。您可以使用componentWillMount而不是componentDidMount,并使用条件呈现:)
componentWillMount(){
this.props.getUser();
if(this.props.user.loading === false && this.props.user.email === undefined){
this.props.history.replace('/Login');
}
}
componentWillReceiveProps(nextProps){
if(nextProps.user.loading === false && nextProps.user.email === undefined){
this.props.history.replace('/Login');
}
}