溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

使用react-router4.0實(shí)現(xiàn)重定向和404功能的方法

發(fā)布時間:2020-10-18 03:11:12 來源:腳本之家 閱讀:223 作者:huruji 欄目:web開發(fā)

在開發(fā)中,重定向和404這種需求非常常見,使用React-router4.0可以使用Redirect進(jìn)行重定向

最常用的就是用戶登錄之后自動跳轉(zhuǎn)主頁。

import React, { Component } from 'react';
import axios from 'axios';
import { Redirect } from 'react-router-dom';

class Login extends Component{
 constructor(){
  super();
  this.state = {value: '', logined: false};
  this.handleChange = this.handleChange.bind(this);
  this.toLogin = this.toLogin.bind(this);
 }
 handleChange(event) {
  this.setState({value: event.target.value})
 }

 toLogin(accesstoken) {
  axios.post('yoururl',{accesstoken})
   .then((res) => {
    this.setState({logined: true});
   })
 }

 render() {
  if(this.props.logined) {
   return (
    <Redirect to="/user"/>
   )
  }
  return (
   <div>
     <input type="text" value={this.state.value} onChange={this.handleChange} />
     <a onClick={() => { this.toLogin(this.state.value) }}>登錄</a>
   </div>
  )
 }
}

export default Login;

以上這個示例僅僅是將登錄的狀態(tài)作為組件的state使用和維護(hù)的,在實(shí)際開發(fā)中,是否登錄的狀態(tài)應(yīng)該是全局使用的,因此這時候可能你會需要考慮使用redux等這些數(shù)據(jù)狀態(tài)管理庫,方便我們做數(shù)據(jù)的管理。這里需要注意的使用傳統(tǒng)的登錄方式使用cookie存儲無序且復(fù)雜的sessionID之類的來儲存用戶的信息,使用token的話,返回的可能是用戶信息,此時可以考慮使用sessionStorage、localStorage來儲存用戶信息(包括頭像、用戶名等),此時書寫reducer時需要指定初始狀態(tài)從存儲中獲取,如:

const LOGIN_SUCCESS = 'LOGIN_SUCCESS';
const LOGIN_FAILED = 'LOGIN_FAILED';
const LOGINOUT = 'LOGINOUT';

const Login = function(state, action) {
 if(!state) {
  console.log('state');
  if(sessionStorage.getItem('usermsg')) {
   return {
    logined: true,
    usermsg: JSON.parse(sessionStorage.getItem('usermsg'))
   }
  }
  return {
   logined: false,
   usermsg: {}
  }
 }
 switch(action.type) {
  case LOGIN_SUCCESS:
   return {logined: true,usermsg: action.usermsg};
  case LOGIN_FAILED:
   return {logined: false,usermsg:{}};
  case LOGINOUT:
   return {logined: false, usermsg: {}};
  default:
   return state
 }
};

export default Login;

指定404頁面也非常簡單,只需要在路由系統(tǒng)最后使用Route指定404頁面的component即可

<Switch>
 <Route path="/" exact component={Home}/>
 <Route path="/user" component={User}/>
 <Route component={NoMatch}/>
</Switch>

當(dāng)路由指定的所有路徑?jīng)]有匹配時,就會加載這個NoMatch組件,也就是404頁面

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI