React project construction and page routing

Posted by rajeevbharti on Tue, 28 Dec 2021 17:38:29 +0100

React project construction

In the use of react framework, react scaffolding is often used to simplify the creation of react projects.

Construction of React scaffold

(1) Global install React scaffold:

npm install -g create-react-app

(2) Build react project - myapp:

npx create-react-app myapp

Other methods:

yarn create react-app myapp

(3) Directory structure of the constructed React project:

(4) Program running:

npm start 

React page routing

From the perspective of users, front-end routing mainly realizes two functions:

  • Record the status of the current page (save the URL of the current page, and when the URL is opened again, the page is still in the saved state)
  • You can use the browser's forward and backward functions

There are two common routing modes: hash mode and history mode

hash mode

hash refers to "#" after the URL address and the characters after it. hash, also known as tracing point, is used for page positioning. It can display the content corresponding to the characters after "#" in the visual area.

The change of hash value will not cause the browser to send a request to the server, and the change of hash will trigger the hashchange event, which can also be controlled by the forward and backward of the browser. Therefore, before the history of html5 appears, hash is often used to realize route jump.

API used:

window.location.hash = 'qq' // Set the hash of the url and add '#qq' after the current url
var hash = window.location.hash // '#qq'
window.addEventListener('hashchange', function(){
    // Listen for hash changes, and click forward and backward of the browser to trigger
})

history mode

Using hash as routing has certain limitations:

  • hash is originally used for page positioning. If it is used as routing, the original tracing function cannot be used.
  • The parameters of hash are based on the URL. There will be volume restrictions on the parameters, but history is different.

The history mode can not only put parameters in the url, but also store the data in a specific object. That is, history mode routing can transfer complex data.

Related API:

 window.history.pushState(state, title, url)
  • State is the data to be saved. This data can be saved again when the pop state event is triggered Get from state
  • Title is the title
  • url is the url to set a new history

For example:

Suppose the current url is: https://www.baidu.com/a/
Execute history After pushstate (null, null, '. / B /'), the url becomes https://www.baidu.com/a/b/.
Execute history Pushstate (null, null, '/ B /'), and the url becomes https://www.baidu.com/b/

Other API s:

window.history.back()   //back off

window.history.forward()    //forward

window.history.go(1)   //One step forward, if - 2, two steps backward
//window.history.length to view the number of pages in the current history stack

React routing

React module for page Routing: react router DOM

Download module:

yarn add react-router-dom

Routing component

(1) The react router DOM has two routing components: HashRouter (hash mode) and BrowserRouter (history mode)

These two components are containers for routing and must be at the outermost layer.

For example:

history mode:

React.render(
	<BrowserRouter>
		<Route path="/" component={Home}/>
	</BrowserRouter>
)

Route

Route is a raw material of routing, which is used to control the correspondence between paths and components.

Relevant parameters:

  • Path: routing path
  • Component: component
  • exact: used for precise positioning

For example:

<Route exact path="/" component={Home}/>
//That is, the contents of the Home component are displayed only when the last path is "/" (the role of exact)

If you do not use exact:

<Route path="/" component={Home}/>
<Route path="/login" component={Login}/>
//Even if the path ends with "/ login", the page displays the contents of the Home component because the path contains "/".

Note: the above expression is ^ 5.2 Version 0 and ^ 5.3 0 version of route writing.
If it is an upgraded version (^ 6.0.2 version), use the following method:

<Routes>
	<Route path='/' element={<Home/>}/>
</Routes>

Link and NavLink

Both Link and NavLink are used to realize route jump, but NavLink has more parameters.

Use to to realize route jump.

<NavLink to='/'>I'll change the page</NavLink>

Redirect page redirection

(1) Basic redirection

<Redirect to="/else" />

(2) Object form

<Redirect
  to={{
    pathname: "/login",
    search: "?utm=your+face",
    state: { referrer: currentLocation }
  }}
/>

(3) Use push to generate new records

<Redirect push to="/else" />

(4) Used with the Switch component, the form represents the path before redirection. If it matches, it will be redirected. If it does not match, it will not be redirected

<Switch>
  <Redirect from='/old-path' to='/new-path'/>
  <Route path='/new-path' component={Place}/>
</Switch>

Switch

Route switching will only match the first route, which can be imagined as a tab column
The Switch can only contain Route, Redirect and Router

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

history object

In each routing component, we can use this props. History gets the history object.

push, replace, go and other methods are encapsulated in history.

History {
    length: number;
    action: Action;
    location: Location;
    push(path: Path, state?: LocationState): void; // Call push to advance to an address and accept a state object, that is, custom routing data
    push(location: LocationDescriptorObject): void; // Accept a description object of location
    replace(path: Path, state?: LocationState): void; // Replace the current path with a page. You can no longer goBack
    replace(location: LocationDescriptorObject): void; // ditto
    go(n: number): void; // How many pages ahead
    goBack(): void; // Return to a page
    goForward(): void; // Advance one page
  
}

Use: this props. history. push('/home')

case

(PS: the old version of react router DOM is used here)

Login component:

export default class Login extends Component{
    constructor(props) {
        super(props);
    }
    login=()=>{
        console.log(this.props.history)
        this.props.history.push('/home')    //Press the url of the home component into the address bar
        console.log(this.props.history)
    }
    render(){
        return(
            <div>
                <h2>Login</h2>
                <p>I'm the landing page</p>
                <Form
                    labelCol={{
                        span: 8,
                    }}
                    wrapperCol={{
                        span: 8,
                    }}

                >
                    <Form.Item label={'user name'}>
                        <Input placeholder={'enter one user name'}/>
                    </Form.Item>
                    <Form.Item label={'password'}>
                        <Input.Password placeholder={'Please input a password'}/>
                    </Form.Item>
                </Form>
                <Button type={'primary'} onClick={this.login}>land</Button>
            </div>
        )
    }
}

Home component:

export default class Home extends Component{
    render() {
        return(
            <BrowserRouter>
                <h2>Home</h2>
                <p>I'm a new page that jumps out</p>
                <div>
                    <ul>
                        <li>
                            <NavLink to={'/home1'}>Level 1 jump routing 1</NavLink>
                        </li>
                        <li>
                            <NavLink to={'/home2'}>Level 1 jump routing 2</NavLink>
                        </li>
                    </ul>
                    <Route path={'/home1'} component={Home1}/>
                    <Route path={'/home2'} component={Home2}/>
                </div>

            </BrowserRouter>
        )
    }
}

Home1 components:

export default class Home1 extends Component{

    render() {
        return(
            <>
                <h3>I am level 1 routing jump page 1</h3>
                <p>The second level jump page is shown below</p>
                <div>
                    <ul>
                        <li>
                            <Link to={`${this.props.match.url}/homes1`}>Secondary routing 1</Link>
                        </li>
                        <li>
                            <Link to={`${this.props.match.url}/homes2`}>Secondary routing 2</Link>
                        </li>
                        <li>
                            <Link to={`${this.props.match.url}/homes3`}>Secondary routing 3</Link>
                        </li>
                    </ul>
                    <Route path={`${this.props.match.url}/homes1`} component={Homes}/>
                    <Route path={`${this.props.match.url}/homes2`} component={Homes2}/>
                    <Route path={`${this.props.match.url}/homes3`} component={Homes}/>
                    <Route exact path={this.props.match.url} render={()=> (
                        <h3>Please select a component</h3>)
                    }/>
                </div>
            </>
        )
    }
}

Homes component:

export default class Homes extends Component{
    render() {
        return(
            <div>
                <h3>Level 2 jump routing page</h3>
            </div>
        )
    }
}

Homes2 component:

export default class Homes2 extends Component{

    render() {
        return(
            <div>
                <h3>Level 2 jump routing page homes2</h3>
            </div>
        )
    }
}

Achieved results:

Topics: Javascript Front-end React