【问题标题】:Uncaught TypeError: Cannot read property 'uid' of undefined未捕获的类型错误:无法读取未定义的属性“uid”
【发布时间】:2018-03-16 21:48:21
【问题描述】:

使用 reactjs、firebase (google auth)、react-router 和 redux 设置身份验证。

问题很简单,但是我在网上找不到任何资源或解决方法。

无法读取 uid(带有 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;
    }
};

【问题讨论】:

  • 需要看看您在商店中如何设置auth
  • 对不起
  • 感谢您的成功!我看不到这个...
  • 我认为这可能是 firebase uid 的问题

标签: javascript reactjs firebase-authentication


【解决方案1】:

Cannot read property 'uid' of undefined - 表示您正在尝试variable.uid 之类的东西,而variable 未定义。根据错误所在的行,state.auth 未定义。

您应该能够在那里查看您的状态,无论是调试还是只是在您的mapStateToProps 中添加一个console.log 以查看您的状态实际上是什么样的:

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
}),

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2017-08-12
      • 2021-12-22
      • 2015-01-06
      • 2017-07-26
      • 2019-02-26
      • 2019-05-09
      • 2021-12-25
      相关资源
      最近更新 更多