React学習ノート4

反応ルーター

 


導入:

1. ルーティングとは、異なる URL アドレスに従って異なるページまたはコンテンツを表示することです

2. インストール: npm install reverse-router-dom@5

使用:

輸入

import {HashRouter, Route} from 'react-router-dom'

 ルートを定義する

   render() {
        return (
            <div>
                <HashRouter>
                    <Route path="/home" component={Home} />
                    <Route path="/second" component={Second} />
                    <Route path="/mine" component={Mine} />
                </HashRouter>    
            </div>
        )
     }

(1) 提案: ルートを js ファイルに個別にカプセル化する

(2) 1次配線と多段配線に注意


リダイレクト

意味: ユーザーに特定のルートにアクセスさせたくない場合、またはそのルートが作成したルートにない場合、指定したルートにコンポーネントをジャンプさせることができます。

//模糊匹配,重定向
   <Redirect from="/" to="/home" exact />
   //exact 精确地
   <Route path="*" component={Text} />

 ネストされたルート

親コンポーネント:

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

サブアセンブリ:

 <Route path="/home/page1" component={Page1} />
 <Route path="/home/page2" component={Page2} />
 <Redirect from="/home" to="/home/page1" />

 ルーティングジャンプ

(1) 宣言型ルーティング

 <NavLink to="/home" activeClassName="ok">home</NavLink>
 <NavLink to="/second" activeClassName="ok">second</NavLink>
 <NavLink to="/mine" activeClassName="ok">mine</NavLink>

(2) プログラムによるルーティング

  • this.props.history.push(ルーティング)
  • props.history.push(ルーティング)
  •  import {useHistory} from 'react-router-dom'
     const history = useHistory()
     history.push(路由)

 ルーティングパラメータ

(1)

<Route path='/detail/:id' component={Detail} />

 動的ルーティング: 動的を表し、ID は置き換え可能であり、props.match.params で取得できます。

(2)

history.push({
    pathname:'/detail',
    query:{id}
  })

props.location.query.id

(3)

history.push({
    pathname:'/detail',
    state:{id}
  })

props.location.state.id


ルートインターセプト

<Route path='/test' render={() => {
    判断 ? <Home/> : <Login/>
  }} />

 ルーティングパターン

  • ハッシュルーター
  • ブラウザルーター

おすすめ

転載: blog.csdn.net/weixin_52993364/article/details/128146376