使用React Router V4重定向

时间:2017-05-08 19:49:02

标签: javascript reactjs react-router react-router-v4

我正在学习React,我的目标是将用户从用户配置文件组件重定向,如果他们当前没有登录。我将用户ID存储在req.session中。以下是相关代码:

userController.js

//user login route
router.post("/api/login", (req, res) => {
    const username = req.body.username;
    const pw = req.body.password;
    db.User.findOne({ where: { username: username } })
        .then((user) => {
            return db.UserPW.findOne({ where: { UserId: user.id } })
                .then((userpw) => {
                    userHelper.passwordCompare(pw, userpw)
                        .then((result) => {
                            if(result) {
                              req.session.user = userpw.UserId;
                              req.session.loggedIn = true;
                              res.json(req.session);
                            } else {
                                req.session.user = 'User Authentication Failed';
                                req.session.loggedIn = false;
                                res.json(req.session);
                            }
                        });

                })
        })
});

//check if user is signed in
router.get("/api/user/status", (req, res) => {
  if(req.session.loggedIn){
    res.json(req.session);
  }else {
    res.json(false);
  }
});

UserProfile.js

import React from 'react';
import { Redirect } from 'react-router-dom';
const userHelper = require('./userHelper');

class UserProfile extends React.Component{
  constructor(){
    super();
    this.state = {
      loggedIn: false
    }
    this.onClick = this.onClick.bind(this);
  }

  onClick(e){
    e.preventDefault();
    userHelper.setAvatarURL(this.state.user, this.url.value)
    .then((avatarResult) => {
      this.setState({ avatar: avatarResult.data.avatar_url });
    });
  }

  componentWillMount(){
    userHelper.status().then((result) => {
      if(result.data){
        this.setState({
          loggedIn: result.data.loggedIn,
          user: result.data.user
        });
        userHelper.userData(result.data.user)
        .then((userResult) =>{
          this.setState({
            email: userResult.data.email,
            first: userResult.data.first_nm,
            last: userResult.data.last_nm,
            zip: userResult.data.zipcode,
            avatar: userResult.data.avatar_url
          });
        });
      }
    });
  }

  render(){
    const login = {
      pathname: '/Login'
    }
    const { redirectToLogin } = this.state.loggedIn;

    if(!redirectToLogin){
      return (
        <Redirect to={login} />
      )
    }

    return (
      <div>
        <img src={this.state.avatar}/>
        <h1>First Name: {this.state.first}</h1>
        <h1>Last Name: {this.state.last}</h1>
        <h1>Email: {this.state.email}</h1>
        <h1>Zip: {this.state.zip}</h1>
        <form>
          <label>Avatar URL: </label>
          <input type="text" ref={(url) => this.url = url} name="url" />
          <button onClick={this.onClick}>Submit</button>
        </form>
      </div>
    );
  }
}

export default UserProfile;

userHelper.js

status: () => {
    return axios.get("/api/user/status")
    .then((result) => {
      return result;
    });
},

userData: (id) => {
  return axios.get("/api/user/" + id)
  .then((result) => {
    return result;
  });
}

我知道UserProfile的render()中的逻辑不起作用,因为它会抛出错误:

warning.js?8a56:36 Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the UserProfile component.

我很可能误解了React语法或组件生命周期的工作原理。感谢您的帮助。

0 个答案:

没有答案