在開發(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)。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注