React-Router实战:重定向Redirect

react

当用户访问某界面时,该界面并不存在,此时用Redirect重定向,重新跳到一个我们自定义的组件里。


一、基础

  • 1、引入使用

// 如果loggedIn 为 false, 则重定向跳转到 /home 页面

import { Route, Redirect } from 'react-router" title="react-router">react-router'

<Route exact path="/" render={() => (

loggedIn ? (

<Redirect to="/home"/>

) : (

<User />

)

)}/>

<Redirect

to={{

pathname: "/login",

search: "?utm=your+face",

state: { referrer: currentLocation }

}}

/>

二、DOME

1、目录结构

| - index.js

| - components

| - App => App.js

| - Home => Home.js

| - About => About.js

| - News => News.js

2、源码

./index.js

import React from 'react';

import ReactDOM from 'react-dom';

import App from './components/App/App';

ReactDOM.render(<App />, document.getElementById('root'));

./components/App/App.js

import React , { Component } from 'react';

import { BrowserRouter as Router, Route, NavLink, Switch, Redirect } from 'react-router-dom';

import Home from '../Home/Home';

import About from '../About/About';

import News from '../News/News';

class App extends Component {

render() {

return (

<Router>

<div>

<li><NavLink to="/">Home</NavLink></li>

<li><NavLink to="/about">About</NavLink></li>

<li><NavLink to="/news">News</NavLink> </li> <br/>

<Switch>

<Route path="/" exact component={Home} />

<Route path="/about" component={About} />

<Route path="/news" component={News} />

<Redirect from="/*" to="/" />

</Switch>

</div>

</Router>

);

}

}

export default App;



./components/About/About.js

import React, { Component } from 'react';

export default class About extends Component {

render() {

return (

<div>

<h2>About</h2>

</div>

);

}

}

./components/New/New.js

import React, { Component } from 'react';

export default class News extends Component {

render() {

return (

<div>

<h2>News</h2>

</div>

);

}

}

3、show

(1)一切功能都是正常,点击About或News就跳转到 About 或 New界面

(2)但当我要在url中,访问: http://localhost:3000/Login

页面立即会重新跳转,跳转回home界面

以上是 React-Router实战:重定向Redirect 的全部内容, 来源链接: utcz.com/z/381727.html

回到顶部