首页 > 解决方案 > 您如何通过将令牌存储在本地存储中来保持用户登录使用?

问题描述

我正在按照本教程实施身份验证: https ://medium.com/technest/implement-user-auth-in-a-django-react-app-with-knox-fc56cdc9211c

当用户访问我的应用程序的基本 url 时,如果他们未通过身份验证,它会将他们重定向到登录页面。这就是我的 app.js 的样子:

class App extends Component {
  componentDidMount() {
    store.dispatch(loadUser());
  }

  render() {
    return (
      <Provider store={store}>
        <Router>
          <Sidebar />
          <Switch>
            <PrivateRoute exact path='/' component={Dashboard} />
            <Route exact path='/feed' component={Feed} />
            <Route exact path='/register' component={RegisterForm} />
            <Route exact path='/login' component={LoginForm} />
            
          </Switch>
        </Router>
      </Provider>

    );
  }
}

export default App;

我的 PrivateRoute.js:

const PrivateRoute = ({ component: Component, auth, ...rest }) => (
  <Route
    {...rest}
    render={props => {
      if (auth.isLoading) {
        return <div>Loading...</div>;
      } else if (!auth.isAuthenticated) {
        return <Redirect to='/login' />;
      } else {
        return <Component {...props} />;
      }
    }}
  />
);

const mapStateToProps = state => ({
  auth: state.auth
});

export default connect(mapStateToProps)(PrivateRoute);

在这里,身份验证工作正常,并正确链接到我的 Dashboard.js 组件。在我的 Dashboard.js 中,我只是渲染了另一个名为 Profile.js 的组件,它显示了用户的个人资料。

在我展示的第一个代码(App.js)中,在标签之外,我有我的 Sidebar.js 组件,无论用户是否登录,它都会始终呈现。

class Sidebar extends Component {
// Button event to switch to feed page.
  render() {
    const { user, isAuthenticated } = this.props.auth;

    return (
        <>
        <div id="sidebar">
            <a onClick={this.props.logout} id="logout_btn">
                <span className="fa fa-lock"></span></a>
            <NavLink id="profile_btn" to="/">
                <span className="fa fa-user-circle"></span></NavLink>
            <NavLink id="feed_btn" to="/feed">
                <span className="fa fa-address-book"></span></NavLink>
        </div>
        <div id="brand">
            <h1>Cook Simple</h1>
            <p id="username-goes-here"></p>
            <a id="add_btn" href="{% url 'recipe:recipe_new' %}">
                <span class="fa fa-plus"></span> </a>
        </div>
        </>
    );
  }
}

const mapStateToProps = state => ({
    auth: state.auth
});

export default connect(mapStateToProps, { logout })(Sidebar);

在这个侧边栏上,我有一个链接到上述配置文件的按钮和另一个链接到另一个名为 Feed 的组件的按钮。单击“个人资料”按钮可以正常工作 - 它转到我的基本网址,该网址转到 PrivateRoute,查看用户已通过身份验证,并呈现个人资料。但是,单击 Feed 按钮显示未定义道具“auth”。饲料的代码:

class Feed extends Component {
  componentDidMount() {
    this.props.getAllRecipes();
  }
  setGrid() {
    try {
      document.getElementById("grid-container-PROFILE").id = "grid-container-FEED"
      console.log("Feed Loaded")
    }
    catch {
      console.log("Feed Already Loaded")
    }
  }

  render() {
    this.setGrid()
    return (
    <>
      <div id="brand">
        <h1>Title Goes Here</h1>
      </div>

      <div className="title-FEED" id="recipecards-FEED">
        <div id="recipecard-container-FEED">
          <RecipeList />
        </div>
      </div>
    </>
    );
  }
}

const mapStateToProps = (state) => {
  return {
    all_recipes: state.all_recipes,
    auth: state.auth
  }
}

const mapDispatchToProps = () => {
  return {
    getAllRecipes,
  }
}

export default connect(mapStateToProps, mapDispatchToProps())(Feed)

在这个组件中,我希望能够访问 auth.user 以在用户对象中呈现一些数据。但是,似乎 auth 是未定义的。

我用于身份验证的操作和减速器与链接教程相同。以下是他们的要点:

身份验证操作:https ://gist.github.com/kjmczk/2c287f1d615824c627580bd2a8067fcb#file-auth-js

身份验证减速器:https ://gist.github.com/kjmczk/64f302546e4cd38ff922cf5d59192b8e#file-auth-js

标签: reactjsreact-redux

解决方案


我发现了这个问题。使用 React DevTools 查看我的 props 时,组件似乎都有auth prop,但每当我尝试实际使用它时,都会出错。我通过仅在检查用户已通过身份验证后访问道具来解决此问题。


推荐阅读