[React Router V4] Create Basic Routes with the React Router v4 BrowserRouter

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[React Router V4] Create Basic Routes with the React Router v4 BrowserRouter相关的知识,希望对你有一定的参考价值。

React Router 4 has several routers built in for different purposes. The primary one you will use for building web applications is the BrowserRouter. In this lesson you will import the BrowserRouter and create some basic Route components.

 

After create your app with \'creat-react-app\', we going to install the react-router-dom:

npm i -D react-router-dom@next

 

Import BrowserRouter:

import {
    BrowserRouter as Router,
    Route
} from \'react-router-dom\';

 

Using Router:

        <Router>
            <div>
                <Route exact path="/" component={App}></Route>
                <Route path="/about" component={About}></Route>
                <Route
                    strict
                    path="/about/"
                    render={() => <h2>About render</h2>}></Route>
                <Route
                    path="/demo"
                    children={({match}) => match && <h2>demo</h2>}></Route>
            </div>
        </Router>

Here we use three different ways to render a component or html to the DOM:

1. Using Component:

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

Here the \'exact\' flag tells that it should match only \'/\'.

 

2. Using render:

we can just render some html:

                <Route
                    strict
                    path="/about/"
                    render={() => <h2>About render</h2>}></Route>

 

3. Using children:

                <Route
                    path="/demo"
                    children={({match}) => match && <h2>demo</h2>}></Route>

By default what we write into \'children\' will be rendered no matter which path it matchs. 

If for example, we only want it to be shown when match \'/demo\', we can check whether there is a \'match\' object exists on props.

以上是关于[React Router V4] Create Basic Routes with the React Router v4 BrowserRouter的主要内容,如果未能解决你的问题,请参考以下文章

React-router v4教程

[React Router v4] Use the React Router v4 Link Component for Navigation Between Routes

React-router-dom (v6) 和 Framer Motion (v4)

react-router 从 v3 版本升到 v4 版本,升级小记

javascript React Router v4 Auth

解决 react-router / react-router-dom v4 history不能访问的问题