Я пытаюсь создать обработчик сеанса для всех компонентов, где мне нужно определить, вошел ли пользователь в систему. Однако, если я добавлю console.log (authUser) в withAuthentication
, он возвращает пользователя, нооднако не в SideBar
.Здесь всегда будет null
.Что я делаю не так?
с аутентификацией
const withAuthentication = (Component) => {
class WithAuthentication extends React.Component {
componentDidMount() {
const { onSetAuthUser } = this.props;
firebase.auth.onAuthStateChanged(authUser => {
authUser
? onSetAuthUser(authUser)
: onSetAuthUser(null);
});
}
render() {
return (
<Component />
);
}
}
const mapDispatchToProps = (dispatch) => ({
onSetAuthUser: (authUser) => dispatch({ type: 'AUTH_USER_SET', authUser }),
});
return connect(null, mapDispatchToProps)(WithAuthentication);
}
export default withAuthentication;
Приложение
class App extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="app">
<SideBar />
<div>
<Navigation/>
<BrowserRouter>
<Switch>
<Route exact path={routes.LANDING} component={() => <LandingPage />} />
<Route render={() => <h3>No Match</h3>} />
</Switch>
</BrowserRouter>
</div>
</div>
)
}
}
export default withAuthentication(App);
SideBar
const INITIAL_STATE = {
sideBarOpen: false
};
class SideBar extends Component {
constructor(props) {
super(props.authUser);
console.log(props)
this.state = { ...INITIAL_STATE };
}
render() {
const {
sideBarOpen,
authUser
} = this.state;
const {
children,
} = this.props;
return (
{authUSer ?
'authed' :
'not authed'
}
)
}
}
const mapStateToProps = (state) => ({
authUser: state.sessionState.authUser
});
export default connect(mapStateToProps)(SideBar);
редуктор
const INITIAL_STATE = {
authUser: null,
};
const applySetAuthUser = (state, action) => ({
...state,
authUser: action.authUser
});
function sessionReducer(state = INITIAL_STATE, action) {
switch(action.type) {
case 'AUTH_USER_SET' : {
return applySetAuthUser(state, action);
}
default : return state;
}
}
const rootReducer = combineReducers({
sessionState: sessionReducer
});
export default rootReducer;