如何通过将令牌存储在本地存储中来保持用户登录使用状态?

时间:2020-08-24 01:07:40

标签: reactjs react-redux

我正在按照本教程实施身份验证: 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的组件。单击“配置文件”按钮可以正常工作-转到我的基本URL,该URL转到“专用路由”,看到用户已通过身份验证,然后呈现“配置文件”。但是,单击Feed的按钮将显示prop'auth'未定义。 Feed的代码:

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

auth reducers:https://gist.github.com/kjmczk/64f302546e4cd38ff922cf5d59192b8e#file-auth-js

2 个答案:

答案 0 :(得分:0)

似乎您有语法错误。 尝试更换:

connect(mapStateToProps, mapDispatchToProps())(Feed);

使用:

connect(mapStateToProps, mapDispatchToProps)(Feed);

删除括号。

答案 1 :(得分:0)

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