【问题标题】:How can I load user every time the page is refreshed?每次刷新页面时如何加载用户?
【发布时间】:2021-06-10 03:05:18
【问题描述】:

我怎样才能为此制作相关的 asp.net 控制器? 我还向 App.js 添加了“加载用户”功能。我想要的是每次刷新页面时加载用户。登录功能正常,但是当页面刷新时,身份验证将再次为空。

"export const loadUser = () => async (dispatch) => {
 if (localStorage.token) {
   setAuthToken(localStorage.token);
     
}

 try {
  const res = await axios.get('https://localhost:5001/api/auth/user');
   dispatch({
    type: USER_LOADED,
    payload: res.data,
   });
} catch (err) {
   dispatch({
     type: AUTH_ERROR,
 });
}
};"

这是登录页面

import React, { useState } from 'react';
import Avatar from '@material-ui/core/Avatar';
import Button from '@material-ui/core/Button';
import TextField from '@material-ui/core/TextField';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Checkbox from '@material-ui/core/Checkbox';
import Link from '@material-ui/core/Link';
import Paper from '@material-ui/core/Paper';
import Box from '@material-ui/core/Box';
import Grid from '@material-ui/core/Grid';
import LockOutlinedIcon from '@material-ui/icons/LockOutlined';
import Typography from '@material-ui/core/Typography';
import { makeStyles } from '@material-ui/core/styles';
import { pink } from '@material-ui/core/colors';
import { connect } from 'react-redux';
import { setAlert } from '../../actions/alert';
import PropTypes from 'prop-types';
import {login} from '../../actions/auth'
import { Redirect } from 'react-router-dom'

function Copyright() {
  return (
    <Typography variant="body2" color="textSecondary" align="center">
      {'Copyright © '}
      <Link color="primary" href="./">
        NoQueue Website
      </Link>{' '}
      {new Date().getFullYear()}
      {'.'}
    </Typography>
  );
}

const useStyles = makeStyles((theme) => ({
  root: {
    height: '100vh',
  },
  image: {
    backgroundImage: 'url(https://invention.si.edu/sites/default/files/styles/story_banner_image/public/blog-guest-fox-susannah-2017-03-09-shutterstock_189632216-banner-edit.jpg?itok=eNxGJoO4)',
    backgroundSize: 'cover',
    backgroundPosition: 'center',
  },
  paper: {
    margin: theme.spacing(8, 4),
    display: 'flex',
    flexDirection:'column',
    alignItems: 'center',
  },
  avatar: {
    margin: theme.spacing(1),
    backgroundColor: pink.A700,
  },
  form: {
    width: '100%',
    marginTop: theme.spacing(2),
  },
  submit: {
    margin: theme.spacing(3,0,2),
  },

}));

const SignIn = ({setAlert,login,isAuthenticated,user}) => {

  const [formData, setFormData] = useState({
    email:"",
    password:"",
  })

const{email,password}=formData; 

const onChange=e=>setFormData(
  {
    ...formData, [e.target.name]:e.target.value
  }
)

const onSubmit=async e=>{

  e.preventDefault();
  if (email && password) {
    login(email,password)
  
  }
        else{
          setAlert('Please fill all the fileds','warning');
        }
      }

     

  const classes = useStyles();


  if(isAuthenticated){

//if(user.role === 'User')
//return <Redirect to="/index"/>
//else if(
//user.role ==='Admin'
//)
    return <Redirect to="/business"/>
  }

  return (
    <Grid container component="main" className={classes.root}>
     
      <Grid item xs={false} sm={4} md={7} className={classes.image} />

      <Grid item xs={12} sm={8} md={5} component={Paper} square>
        <div className={classes.paper}>

          <Avatar className={classes.avatar}>
            <LockOutlinedIcon />
          </Avatar>

          <Typography component="h1" variant="h5">
            Sign in
          </Typography>

          <form onSubmit = { e=>onSubmit(e)} className={classes.form} noValidate>
            <TextField
            onChange={e=>onChange(e)}
              variant="outlined"
              margin="normal"
              required
              fullWidth
              id="email"
              label="Email Address"
              name="email"
              value={email}
            />

            <TextField
            onChange={e=>onChange(e)}
              variant="outlined"
              margin="normal"
              required
              fullWidth
              name="password"
              label="Password"
              type="password"
              id="password"
              value={password}
            />

            <FormControlLabel
              control={<Checkbox value="remember" color="primary" />}
              label="Remember me"
            />

            <Button
              type="submit"
              fullWidth
              variant="contained"
              color="Primary"
              className={classes.submit}
            >
              Sign In
            </Button>

            <Grid container>
              <Grid item xs>
                <Link href="forgotpassword" variant="body2">
                  Forgot password?
                </Link>
              </Grid>
              <Grid item>

                <Link href="signup" variant="body2">
                  {"Not a member? Sign Up"}
                </Link>
              </Grid>
            </Grid>
            
            <Box mt={5}>
              <Copyright />
            </Box>

          </form>
        </div>
      </Grid>
    </Grid>
  );
}

SignIn.propTypes={
  login:PropTypes.func.isRequired,
  setAlert:PropTypes.func.isRequired,
  isAuthenticated:PropTypes.bool,
  user: PropTypes.object.isRequired,
};

const mapStateToProps=state=>({
  isAuthenticated:state.auth.isAuthenticated,
  user: state.auth.user,
})


export default connect(mapStateToProps,{login,setAlert})(SignIn);


【问题讨论】:

  • 看起来问题与C 无关。请检查该标签。
  • 您不需要每次都从控制器加载用户。将身份验证数据存储到本地存储,即 cookie,然后检查该数据。如果您发布成功登录后加载主页的代码,我将向您展示如何做
  • 我已经添加了登录页面。

标签: javascript c# node.js asp.net reactjs


【解决方案1】:

我认为在 redux 的初始状态下,您需要检查 localStorage.token 是否不为空/过期并将其设置回用户。这样每当您刷新页面时,用户 da 仍然可以加载

【讨论】:

    【解决方案2】:

    我能够通过使用 jwt_decode 解决上述问题

      if (localStorage.token) {
        setAuthToken(localStorage.token);
        var decoded = jwt_decode(localStorage.token);
       
    }
    
      try {
       const res = await axios.get(`https://localhost:5001/api/auth/user/${decoded.Id}`);
        dispatch({
         type: USER_LOADED,
         payload: res.data,
        });
     } catch (err) {
        dispatch({
          type: AUTH_ERROR,
      });
    }
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-17
      • 1970-01-01
      • 2020-11-08
      • 2014-02-16
      • 1970-01-01
      • 2017-04-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多