国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > JavaScript > 正文

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

2019-11-19 15:39:15
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

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

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

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;

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

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頁(yè)面也非常簡(jiǎn)單,只需要在路由系統(tǒng)最后使用Route指定404頁(yè)面的component即可

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

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

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 剑阁县| 南华县| 宁武县| 修武县| 察雅县| 竹北市| 清涧县| 樟树市| 清新县| 乐昌市| 玉环县| 稷山县| 吕梁市| 汕尾市| 阳江市| 马鞍山市| 东方市| 桓台县| 南川市| 福鼎市| 塔城市| 衡山县| 阳山县| 旬阳县| 二手房| 兴化市| 秭归县| 麻栗坡县| 大悟县| 长兴县| 瑞金市| 崇信县| 滨州市| 龙门县| 隆回县| 家居| 肃南| 台南市| 行唐县| 察隅县| 贡山|