MENU

React学习笔记【16】

第十九节

React路由

重定向组件

访问某个组件时,如果有重定向组件,那么就会修改页面路径,使得页面内容显示为所定向的内容

Switch

让Switch组件内的Route只匹配一个,只要匹配到了,剩余路由规则将不再匹配

本节代码

import React from "react"
import { BrowserRouter as Router, Route, Link, Redirect, Switch } from 'react-router-dom'

function LoginInfo(props) {
    // props.loginState = 'success';
    // props.loginState = 'failed';
    console.log(props);
    if (props.location.state.loginState == 'success') {
        return <Redirect to="/admin"></Redirect>
    } else {
        return <Redirect to="/login"></Redirect>
    }
}

let FormCom = () => {
    let pathObj = {
        pathname: "/loginInfo",
        state: {
            loginState: 'success'
        }
    }
    return (
        <div>
            <h1>表单验证</h1>
            <Link to={pathObj}>登录验证后页面</Link>
        </div>
    )
}

class ChildCom extends React.Component {
    clickEvent = () => {
        console.log(this.props);
        // this.props.history.push("/", { msg: "由ChildCom发给首页的数据" });
        this.props.history.replace("/", { msg: "由ChildCom发给首页的数据" });
        //前进
        // this.props.history.go(1);
        // this.props.history.goForward();
        //后退
        // this.props.history.go(-1);
        // this.props.history.goBack();
    }
    render() {
        return (
            <div>
                <button onClick={this.clickEvent}>跳转到首页</button>
            </div>
        )
    }
}

class App extends React.Component {
    render() {
        return (
            <div>
                <Router>
                    <Route path="/:id" exact component={(props) => { console.log(props); return (<h1>首页</h1>) }}></Route>
                    <Route path="/form" exact component={FormCom}></Route>
                    <Route path="/login" exact component={() => (<h1>登录页</h1>)}></Route>
                    <Route path="/loginInfo" exact component={LoginInfo}></Route>
                    <Route path="/admin" exact component={() => (<h1>admin页,登录成功</h1>)}></Route>
                    <Switch>
                        <Route path="/abc" exact component={() => (<h1>abc页1</h1>)}></Route>
                        <Route path="/abc" exact component={() => (<h1>abc页2</h1>)}></Route>
                    </Switch>
                    <Route path="/child" exact component={ChildCom}></Route>
                </Router>

            </div>
        )
    }
}

export default App

文章标题:React学习笔记【16】
如果文中内容侵犯了您的权益,请及时与博主取得联系进行删除!
本站文章未经许可禁止转载,本文地址:https://blog.wanvale.com/archives/278/

Archives QR Code Tip
QR Code for this page
Tipping QR Code