首頁 > web前端 > js教程 > 主體

react-router4.0實作重新導向與404功能

php中世界最好的语言
發布: 2018-04-18 16:37:15
原創
2229 人瀏覽過

次帶給大家react-router4.0實作重定向與404功能。 react-router4.0實作重定向與404功能的注意事項有哪些,以下就是實戰案例,一起來看一下。

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

最常用的就是使用者登入之後自動跳轉首頁。

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 (
   <p>
     <input type="text" value={this.state.value} onChange={this.handleChange} />
     <a onClick={() => { this.toLogin(this.state.value) }}>登录</a>
   </p>
  )
 }
}
export default Login;
登入後複製

以上這個範例只是將登入的狀態當作元件的state使用和維護的,在實際開發中,是否登入的狀態應該是全域使用的,因此這時候可能你會需要考慮使用redux等這些資料狀態管理庫,方便我們做數據的管理。這裡需要注意的使用傳統的登入方式使用cookie儲存無序且複雜的sessionID之類的來儲存使用者的信息,使用token的話,返回的可能是使用者訊息,此時可以考慮使用sessionStorage、localStorage來儲存使用者資訊(包括頭像、使用者名稱等),此時書寫reducer時需要指定初始狀態從儲存中獲取,如:

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頁面也非常簡單,只需要在路由系統最後使用Route指定404頁面的component即可

<Switch>
 <Route path="/" exact component={Home}/>
 <Route path="/user" component={User}/>
 <Route component={NoMatch}/>
</Switch>
登入後複製

當路由指定的所有路徑沒有匹配時,就會加載這個NoMatch組件,也就是404頁面

相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!

推薦閱讀:

js原型物件使用的步奏詳解

js設定元素樣式步奏詳解

以上是react-router4.0實作重新導向與404功能的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!