我正在尝试为所有需要确定用户是否登录的组件创建会话处理程序。但是,如果我在withAuthentication
中添加console.log(authUser),它将返回一个用户,但不在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);
侧边栏
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;
答案 0 :(得分:0)
作为您的mapStateToProps
设置
const mapStateToProps = (state) => ({
authUser: state.sessionState.authUser
});
您需要从组件authUser
中获取props
,而不是从组件state
中获取。
因此您的代码应为const authUser = this.props.authUser
。
或者按照您的方式const {authUser} = this.props