如何使用json stringify将用户令牌存储在react js中?

时间:2019-11-28 10:33:29

标签: reactjs redux react-redux authorization local-storage

我一直在尝试使用redux将用户令牌存储在react js中,我希望用户一直停留在同一页面上,直到令牌存储在本地存储中,但是我一直在努力地知道要在哪里编写代码存储令牌。我一直在尝试使用用户令牌进行身份验证,因为我获得了我选择的值作为输入,我如何通过将其存储在本地存储中来对其进行身份验证。 我的身份验证/操作

        import React from "react";


        export const loginUser = (data) => dispacth=>{

            if(data.email == "admin@admin.com" && data.password == "123"){

                dispacth({
                    type:CLEAR_ERROR,
                    payload:{}
                })
                dispacth(setCurrentUser({email:data.email,password:data.password}));
                // history.push()
            }else{
                dispacth({
                    type: ERROR,
                    payload: {error:"Invalid Email or Passowrd"}
                })
            }
        }
        export const setCurrentUser = decoded => {
            return {
                type: AUTH,
                payload: decoded
            };
        };

        export function getData() {
            return { type: "DATA_REQUESTED" };
          }
        export const logout = () => dispacth=>{
            dispacth(setCurrentUser({})); 
        } ```

我的Login.jsx

        import {Container,Col,Row} from 'react-bootstrap';
        import 'antd/dist/antd.css';
        import { Card, Input, Icon, Button, Alert } from "antd";
        import axios from 'axios'
        import PropTypes from 'prop-types';
        import { connect } from "react-redux";
        import {loginUser} from '../../Actions/authAction';


        import {Link, Redirect} from 'react-router-dom';

        class Login extends Component {
            constructor(){
                super();
                this.state = {
                    users: [],
                    email: '',
                    password: '',
                    error:'',

                }
            }

                componentDidMount(){

                if  (this.props.auth.isAuthenticated) {
                    this.props.history.push('/dashboard');
                }

            }

            componentWillReceiveProps(nextProps){
                if (nextProps.auth.isAuthenticated) {
                    this.props.history.push('/dashboard') 
                    console.log(nextProps)
                }
                if (nextProps.error) {
                    this.setState({ error: nextProps.error.error });     
                }

                    if(localStorage.getItem('data')){
                        this.props.history.push('/dashboard');
                    }

            }


            onSubmit = e =>{
                e.preventDefault();

                if (!this.validateEmail(this.state.email)) {
                    this.setState({ isValid: true });
                } else if (this.validateEmail(this.state.email)) {
                    this.setState({ isValid: false });
                    let data = {
                        email: this.state.email,
                        password: this.state.password

                    };
                        this.props.loginUser(data)
                    //     localStorage.setItem('data', this.state.email)
                    //     localStorage.setItem('password', this.state.password)
                    //     localStorage.getItem('data', this.state.email)
                    //    localStorage.getItem('password', this.state.password)
                }


            }
            onChange = e =>{
                this.setState({ [e.target.name]: e.target.value });
            }
            validateEmail = email => {
                var re = /\S+@\S+\.\S+/;
                return re.test(email);
            };
            render() {

                return (
                    <div  >

                    <div >
                        <Container>
                        <h1
                            className='text-center'
                            style={{ marginTop: "5%", marginBottom: "3%" }}>

                        </h1>
                        <Row>
                            <Col lg={3}></Col>
                            <Col lg={5}>
                            <Card className='example z-depth-1'
                                title={<h3 className='text-center'>Login</h3>}
                                bordered={true}
                                style={{ width: "99%" }}>
                            {this.state.isValid ? (
                            <Alert
                                style={{ marginBottom: "10px" }}
                                message='Your email is invalid'
                                type='error'
                                showIcon
                            />
                            ) : null}
                            <div>{this.state.error}</div>
                            <Input
                                placeholder="Email Address"
                                name="email"
                                type="email"
                                value={this.state.email}
                                onChange={this.onChange}
                                size='large'
                                prefix={
                                    <Icon type='mail' style={{ color: "rgba(0,0,0,.25)" }} />
                                }
                            />
                            <br />
                            <br />
                            <Input
                                placeholder="Password"
                                name="password"
                                type="password"
                                value={this.state.password}
                                onChange={this.onChange}
                                size='large'
                                prefix={
                                    <Icon type='lock' style={{ color: "rgba(0,0,0,.25)" }} />
                                }
                            />
                            <br />
                            <br />
                            <Button
                                type='primary'
                                block
                                size='large'
                                onClick={this.onSubmit}>
                                LOGIN
                            </Button>
                            </Card>
                            </Col>
                        </Row>
                        </Container>
                </div>
                </div>
                )
            }
        }
        Login.propTypes = {
            loginUser: PropTypes.func.isRequired,
            auth: PropTypes.object.isRequired,
            error: PropTypes.object.isRequired
        };
        const mapStateToProps = state => ({
            auth: state.auth,
            error: state.error
        });
        export default connect(mapStateToProps,{loginUser})(Login);  

我的身份验证/还原器

```import {AUTH,ERROR} from '../Actions/type';
    import isEmpty from '../validation/is-empty';
    const initialState = {
        isAuthenticated:false,
        user:{}
    }
    export default function(state=initialState,action){
        switch(action.type){
            case AUTH:
                return{
                    ...state,
                    isAuthenticated:!isEmpty(action.payload),
                    user:action.payload
                }
            default:
                return state;
        }
    }   

0 个答案:

没有答案