使用reactjs,firebase(google auth),react-router和redux设置身份验证。
问题非常简单,但我找不到任何在线资源或解决问题的答案。
无法阅读uid的roperty(使用firebase的用户ID),因为它告诉我它未定义?我已经设置了私有路由是一个新组件,它已经在我的应用路由器中导入。我也计划有一条公共路线。
这是我的代码以及错误的屏幕截图。
PrivateRoute.js
import React from 'react';
import { connect } from 'react-redux';
import { Route, Redirect } from 'react-router-dom';
export const PrivateRoute = (props) => (
<Route {...props} />
);
const mapStateToProps = (state) => ({
isAuthenticated: !!state.auth.uid <-error on this uid
});
export default connect(mapStateToProps)(PrivateRoute);
AppRouter.js
import PrivateRoute from './PrivateRoute'
<Route path="/" component={Login} exact={true}/>
<PrivateRoute path="/dashboard" component={Dashboard} />
<PrivateRoute path="/create" component={AddExp}/>
我退出并尝试访问/create
私有路径时出现错误的屏幕截图
已更新以添加redux store配置文件
import authenticationReducer from '../reducers/authentication'
export default () => {
const store = createStore(
combineReducers({
expenses: expensesReducer,
authentication: authenticationReducer
}),
composeEnhancers(applyMiddleware(thunk))
);
return store;
};
Auth reducer(只是需要它)
export default (state = {}, action) => {
switch (action.type) {
case 'LOGIN':
return {
uid: action.uid
};
case 'LOGOUT':
return {
};
default:
return state;
}
};
答案 0 :(得分:1)
您在uid
上设置state.authentication.uid
并尝试从state.auth.uid
答案 1 :(得分:1)
Cannot read property 'uid' of undefined
- 表示您尝试variable.uid
和variable
之类的内容未定义。根据带错误的行,state.auth
未定义。
你应该能够在那里查看你的状态,调试或只是在你的console.log
中抛出一个mapStateToProps
来查看你的状态实际上是什么样的:
const mapStateToProps = (state) => {
console.log('state:', state); // see what state is
return {
isAuthenticated: !!state.auth.uid <-error on this uid
};
}
查看combineReducers
似乎是将authenticationReducer
的结果放到state.authentication
上,而不是state.auth
...
combineReducers({
expenses: expensesReducer,
authentication: authenticationReducer
}),