在React JS中刷新页面后如何保持登录

时间:2019-09-20 07:32:49

标签: reactjs

刷新页面时出现问题,页面自动返回错误的isLogin。我不知道,我已经尝试了很多次,并要求stackoverflow但没有结果。据我们所知 。如果我们尝试编辑代码并保存,浏览器将刷新页面。然后尝试尝试操作道具isloggin,当我登录时返回true,但刷新页面时返回false。 @。@

index.js

import React from "react";
import ReactDOM from "react-dom";
import { createStore } from 'redux'
import { Provider } from 'react-redux'
import { Router, Route, Switch} from "react-router-dom";
import { createHashHistory } from 'history';

import "assets/vendor/nucleo/css/nucleo.css";
import "assets/vendor/@fortawesome/fontawesome-free/css/all.min.css";
import "assets/scss/argon-dashboard-react.scss";

import AdminLayout from "layouts/Admin.js";
import reducer from './components/reducers'
import LandingLogin from './layouts/LandingLogin.js'
import LandingRegister from './layouts/LandingRegister.js'


const store = createStore(reducer);
const customHistory = createHashHistory();



ReactDOM.render(
  <Provider store = {store}>
      <Router history={customHistory}>
        <Switch>
          <Route path="/admin" render={props => <AdminLayout {...props} />} />
          <Route exact path="/" render= {() => <LandingLogin/>} />
          <Route exact path="/login" render= {() => <LandingLogin/>} />
          <Route exact path="/register" render= {() => <LandingRegister/>} />
        </Switch>
      </Router>
  </Provider>,
  document.getElementById("root")
);

login.js

import React, { Fragment } from 'react'
import { connect } from 'react-redux'
import { userLogin } from '../../actions/index'
import axios from 'axios';
import { createHashHistory } from 'history';

// reactstrap components
import {
  Button,
  Card,
  CardBody,
  FormGroup,
  Form,
  Input,
  InputGroupAddon,
  InputGroupText,
  InputGroup,
  Col
} from "reactstrap";

const customHistory = createHashHistory();

class Login extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        post : [],
        formData : {
          id : '',
          first_name : '',
          last_name : '',
          email : '',
          gender : '',
          password: '',
        },
        isLogedIn : true

      }
      this.handleForm = this.handleForm.bind(this);
      this.submitLogin = this.submitLogin.bind(this);
    }

    getPostAPI = () => {
      axios.get('http://localhost:8001/datauser')
      .then((res) => {
          this.setState ({
              post : res.data
          })
      })
    }

    getPostAPI2 = () => {
      axios.get('http://localhost:8001/dataadmin')
      .then((res) => {
          this.setState ({
              post : res.data
          })
      })
    }

    handleForm = (e) => {
      let formDataNew = {...this.state.formData};
      formDataNew[e.target.name] = e.target.value;
      this.setState({
        formData : formDataNew
      })

    }

    loadValues = () => {
      this.setState({
        formData: [`{"email": "${this.state.formData.email}","password": "${this.state.formData.password}"}`],
      }, () => {
        sessionStorage.setItem('formData', this.state.formData)
      })
    }

    submitLogin = (event) => {
      const { dispatch } = this.props;
      const {post} = this.state;    
      if(post.find(e =>  `${e.email}${e.password}` === `${this.state.formData.email}${this.state.formData.password}` )) {
        dispatch(userLogin(this.state.formData.email, this.state.formData.password));
        this.loadValues();
              customHistory.push('/admin/index');
      }else  {
        alert("Email atau Password Salah!");
        this.setState ({
          formData : {
            email : '',
            password: ''
          },


        })

      }
    }

    componentDidMount () {
      this.getPostAPI2();
    }

    render() {
        return (
            <Fragment>
              <Col lg="5" md="7">
                <Card className="bg-secondary shadow border-0">
                  <CardBody className="px-lg-5 py-lg-5">
                  <div className="text-center text-muted mb-4">
                      <h2>Form Login</h2>
                  </div>
                    <Form role="form">
                      <FormGroup className="mb-3">
                        <InputGroup className="input-group-alternative">
                          <InputGroupAddon addonType="prepend">
                            <InputGroupText>
                              <i className="ni ni-email-83" />
                            </InputGroupText>
                          </InputGroupAddon>
                          <Input onChange={this.handleForm} value={this.state.formData.email} name = "email" placeholder="Email" type="email" />
                        </InputGroup>
                      </FormGroup>
                      <FormGroup>
                        <InputGroup className="input-group-alternative">
                          <InputGroupAddon addonType="prepend">
                            <InputGroupText>
                              <i className="ni ni-lock-circle-open" />
                            </InputGroupText>
                          </InputGroupAddon>
                          <Input onChange={this.handleForm} value={this.state.formData.password} name = "password" placeholder="Password" type="password" />
                        </InputGroup>
                      </FormGroup>
                      <div className="custom-control custom-control-alternative custom-checkbox">
                        <input
                          className="custom-control-input"
                          id=" customCheckLogin"
                          type="checkbox"
                        />
                        <label
                          className="custom-control-label"
                          htmlFor=" customCheckLogin"
                        >
                          <span className="text-muted">Remember me</span>
                        </label>
                      </div>

                      <div className="text-center">
                        <Button onClick={this.submitLogin} className="my-4" color="primary" type="button">
                        Log in
                      </Button>
                      </div>
                    </Form>
                  </CardBody>
                </Card>
              </Col>

            </Fragment>
          );
        }
      }

      function select(state) {
        return {
          users: state.users
        }
      }

      export default connect(select)(Login);

reducers users.js



import { USER_LOGIN, USER_LOGOUT} from '../../constants/ActionTypes';


const initialState = {
    isLoggedIn: false
  }


export default function users(state = initialState, action) {
  switch (action.type) {
    case USER_LOGIN:
        return Object.assign({}, state, response(state, action));
    case USER_LOGOUT:
        return Object.assign({}, state, logout());

    default:
      return state
  }

function response(state){

  state.isLoggedIn = true;
  return state

}

function logout(){
    state.isLoggedIn = false;
    return state;
    }
}

actiontype.js

export const USER_LOGIN = 'USER_LOGIN'
export const USER_LOGOUT = 'USER_LOGOUT'

actions.js

import { USER_LOGIN, USER_LOGOUT} from '../constants/ActionTypes'

export function userLogin(email, password) {
    return {
        type: USER_LOGIN,
        email: email,
        password: password,
    };
}

export function userLogout() {
    return {
        type: USER_LOGOUT
    };
}

如果我要怎么做,我会很高兴,

1 个答案:

答案 0 :(得分:0)

看看包redux-persist。它包含一个函数persistStorePersistGate组件。重新加载页面后,这将为商店补水。并且您必须选择在浏览器中存储数据将被保存。您可以在会话存储(每个选项卡)或语言环境存储(每个域)之间进行选择

以下是会话存储的示例

import { PersistGate } from 'redux-persist/lib/integration/react'
import { persistStore } from 'redux-persist'
import { persistReducer } from 'redux-persist'
import storage from 'redux-persist/es/storage/session'

const persistConfig = {
    key: 'root',
    storage,
}

const persistedReducer = persistReducer(persistConfig, reducer)

const store = createStore(persistedReducer);
const persistor = persistStore(store)
const customHistory = createHashHistory();



ReactDOM.render(
  <Provider store = {store}>
        <PersistGate persistor={persistor}>
...