Analysis of React Routing principle

Source: Internet
Author: User

Rationale: After DOM rendering is complete, add the "Hashchange" event to the window to listen for changes to the page hash, and add the route attribute to the State property, which represents the route of the current page.

1, when clicked the Connection page hash change, triggers binds in the window the Hashchange event,

2. Change the route attribute in the state of the component in the Hashchange event (the page is automatically rendered when the State property of the react component changes)

3, the page with the state of the route attribute change automatically according to the constant hash to the child variable assignment of components, rendering

Core code:

import react from ' react ' import {render} from ' React-dom '

Const about = function () {return &L T div>111</div>} Const Inbox = function () {return < div>222</div>} Const HOME = function () {RET Urn < div>333</div>}
Class App extends react. Component {
state = {Route:window.location.hash. substr (1)}
Componentdidmount () {window. AddEventListener ( ' Hashchange ', () => {this. setstate ({route:window.location.hash. substr (1)})}
Render () {Let child switch (this.state.route) {case '/about ': a child = about; a break; a case '/inbox ': a child = a inbox; break; default:child = home;}
Return (< div> < h1>app Render (< App/>, document.body)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.