简体   繁体   English

每次刷新页面时如何加载用户?

[英]How can I load user every time the page is refreshed?

How can i make the relevant asp.net controller for this?我怎样才能为此制作相关的 asp.net controller? I have added the 'load user' functions to App.js also.我还向 App.js 添加了“加载用户”功能。 What I want is to load the user every time the page is refreshed.我想要的是每次刷新页面时加载用户。 The login function is working properly but when the page is refreshed the authentication will be null again.登录 function 工作正常,但刷新页面时,身份验证将再次为 null。

"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,
 });
}
};"

This is the login page这是登录页面

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);


I think in initial state of redux you need to check whether or not localStorage.token is not null/expired and set it back to user.我认为在 redux 的初始 state 中,您需要检查 localStorage.token 是否不为空/过期并将其设置回用户。 So that whenever you refresh the page user da still can load这样每当您刷新页面时,用户 da 仍然可以加载

I was able to resolve above issue by using jwt_decode我能够通过使用 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,
  });
}
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 每次刷新页面时,如何为一行文本生成随机字体? - How do I generate a random font to a line of text every time page is refreshed? 每次刷新页面时运行的JSP函数 - JSP function running every time page is refreshed 每次加载时页面都会刷新 - the page is refreshed every time when is loaded 防止每次加载页面时刷新JavaScript - Prevent JavaScript to be refreshed every time the page is loaded 每次刷新页面时调用终端命令 - Call terminal command every time page is refreshed 每当用户点击页面底部时,如何迭代此函数以进行ajax调用? - How can I iterate this function to make the ajax call every time the user hits the bottom of the page? 每次用户被定向到视图/页面时,如何让我的 Javascript 不弹出 - How can I make my Javascript not pop up every time a user gets directed to the a View/Page JS,如何理解页面是刷新还是第一次打开? - JS, How can understood page is refreshed or first time opened? 如何导航到页面,但要确保目标页面将被刷新 - how can I navigate to page but ensure that the target page will be refreshed 每次用户加载页面时,如何存储整个Javascript文件并加载更改的版本? - How can I store an entire Javascript file and load the changed version each time the user loads the page?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM