未捕获的TypeError:无法读取未定义的属性'uid'

时间:2018-03-16 21:48:21

标签: javascript reactjs firebase-authentication

使用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私有路径时出现错误的屏幕截图

Console errors: chrome

已更新以添加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;
    }
};

2 个答案:

答案 0 :(得分:1)

您在uid上设置state.authentication.uid并尝试从state.auth.uid

访问它

答案 1 :(得分:1)

Cannot read property 'uid' of undefined - 表示您尝试variable.uidvariable之类的内容未定义。根据带错误的行,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
}),