简体   繁体   中英

Understanding basics of reach router

I am trying to understand basics of reach router and have doubts on following code

import React from "react";
import { render } from "react-dom";
import Logo from "./Logo";
import { Router, Link } from "@reach/router";

let Home = () => (
  <div>
    <h1>Home</h1>
    <nav>
      <Link to="/">Home</Link> |{" "}
      <Link to="/dashboard">Dashboard</Link>
    </nav>

  </div>
)

let Dash = () => <div>Dash</div>



render(<Router>
  <Home path="/" />
  <Dash path="dashboard" />
</Router>, document.getElementById("root"));

I know that this Router works as Switch from router 4, ie, renders only one path inside router. Now when I start the app initially I am inside Home , eg here

<div>
    <h1>Home</h1>
    <nav>
      <Link to="/">Home</Link> |{" "}
      <Link to="/dashboard">Dashboard</Link>
    </nav>

  </div>

At this moment it is my belief that Dashboard component hasn't been rendered anywhere. However, if I type dashboard in URL or click the above link it correctly takes me to Dashboard component.

My question is how does algorithm of resolving to Dashboard works in this case? Does it "restart" the app and see that there was a component registered for "dashboard" route initially? My point is because when I am at home location there is nothing on the page anymore that indicates that Dashboard component is registered under dashboard route, or I am wrong?

<Router> 's internal implementation uses history.listen() ( https://github.com/reach/router/blob/master/src/index.js#L103 ) which in turn listens to native popstate events ( https://developer.mozilla.org/en-US/docs/Web/Events/popstate ). You can see it in action here .

It looks like your intuitions are indeed right. <Router> component is history-aware by listening to history changes. It re-renders routes as a result of internal setState calls.

I can recommend going though the source code if you'd like to know even more about implementation details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM