Reactjs 反应路由器身份验证失败

Reactjs react-router Authenticate failling

我是 ReactJS 的新手,很抱歉,如果之前有人问过这个问题,我不知道从哪里开始。

我遵循了以下方面的 Auth 指南: https://reacttraining.com/react-router/web/example/auth-workflow

我正在使用 react-router 来处理 ReactJS 的导航,我有一个处理导航的 index.js 文件,其中包括:

import {BrowserRouter, Redirect, Route} from 'react-router-dom';
import Auth from './components/Auth';

const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={props => (
    Auth.authenticate((auth) => {
      if (auth) {
        (<Component {...props}/>)
      }
      else {
        (<Redirect to={{
          pathname: '/',
          state: { from: props.location }
        }}/>)
      }
    })
  )}/>
)

const App = () => (<BrowserRouter>
  <div>
    {/* PUBLIC */}
      <Route path={'/'} exact component={Inicio}/>
      <Route path={'/login'} component={Login}/>

    {/* PRIVATE */}
      <PrivateRoute path="/dashboard" component={Dashboard}/>

  </div>
</BrowserRouter>);

ReactDOM.render(<App/>, document.getElementById('root'));

导航正常,但 Auth.authenticate((auth).. 中的身份验证无法正常工作并引发错误。

它指的是具有以下内容的文件:

import React from 'react';
import http from '../services/http';

const Auth = {
  authenticate(cb) {
    http.authenticate((e, auth) => {
      if (auth === true) {
        cb(true);
      }
      else {
        cb(false);
      }
    });
  }
}

export default Auth;

http.aunthenticate 是一种带有回调的方法,效果很好。

但我在控制台中收到以下错误消息:

> The above error occurred in the <Route> component:
>     in Route (created by PrivateRoute)
>     in PrivateRoute (created by App)
>     in MuiThemeProvider (created by App)
>     in div (created by App)
>     in Router (created by BrowserRouter)
>     in BrowserRouter (created by App)
>     in App
> 
> Consider adding an error boundary to your tree to customize error
> handling behavior. Visit https://reactjs.org/docs/error-boundaries.html to learn
> more about error boundaries. react-dom.development.js:9747 Error:
> Route(...): Nothing was returned from render. This usually means a
> return statement is missing. Or, to render nothing, return null.

有什么想法吗?谢谢!

您的 PrivateRoute 组件从来没有 return 任何东西。 Auth.authenticate((auth) =>... 这是异步的,因此就 render 响应而言,就好像您的方法是空的一样。您应该避免这样做,只需使用 属性 来检测该帐户是否已登录。例如,这就是我使用 Facebook 的 Flux 商店编写我的 PrivateRoute 组件的方式。

const PrivateRoute = ({ component: Component, ...rest }) => (
    <Route {...rest} render={props => (
      AccountStore.loggedIn ? (
        <Component {...props} />
      ) : (
          <Redirect to={{
            pathname: '/signin',
            state: { from: props.location }
          }} />
        )
    )} />
  )

这里我的组件总是 return 一些基于在呈现之前计算的帐户状态的东西。

编辑:在下面添加我的 AccountStore 以便更清楚地了解细节,这里我使用通过远程 api 进行身份验证后收到的 jwt 令牌,并使用它是否已设置来确定用户是否登录与否。但是,它可以是您选择的任何 property/value。甚至可以是 class 没有连接到任何东西,只是通过几种方法翻转用户登录状态。

import Immutable from 'immutable';
import { ReduceStore } from 'flux/utils';
import AccountActionTypes from './AccountActionTypes';
import CoreDispatcher from '../CoreDispatcher';

import LocalStorage from '../../io/LocalStorage';

class AccountStore extends ReduceStore {
  constructor() {
    super(CoreDispatcher);

    this._jwt = LocalStorage.getItem('jwt');
  }

  getInitialState() {
    return Immutable.OrderedMap({
      jwt: this._jwt,
    });
  }

  reduce(state, action) {
    switch (action.type) {
      case AccountActionTypes.USER_DETAILS_IN:
        console.log('user details in');
        this._user = action.user;
        return state.set('user', this._user);

      case AccountActionTypes.USER_LOGGED_IN:
        this._jwt = action.jwt;
        return state.set('jwt', this._jwt);

      case AccountActionTypes.USER_LOGGED_OUT:
        this._jwt = null;
        return state.set('jwt', this._jwt);

      default:
        return state;
    }
  }

  get jwt() {
    return this._jwt;
  }

  get loggedIn() {
    return !!this._jwt;
  }
}

export default new AccountStore();

有关使用 Flux Stores 和 Dispatcher 的更多详细信息:https://facebook.github.io/flux/

这像是一个简单的语法错误:

const Auth = {
  authenticate(cb) {
    http.authenticate((e, auth) => {
      if (auth === true) {
        cb(true);
      }
      else {
        cb(false);
      }
    });
  }
}

您需要将 Auth 定义为有效的 React 组件(class 或函数)。您所拥有的不是有效的 class、函数或对象。

更重要的是,如果 Auth 没有渲染一些 jsx,那么它不应该是 React 组件。 HTTP 请求应定义为 class 方法,并在生命周期挂钩内部调用,最常见的是 componentDidMount()Article explaining how to make AJAX requests in react.