Stanford CS142 笔记 - Single Page Application

Introduction

In a traditional web app, changing the URL usually means sending a request to the server for a new HTML document.

In contrast, SPAs generally involve a single HTML file that serves as the structure for the entire app. Once loaded, this file stays in place, and JavaScript handles any further changes to the page’s content. SPAs dynamically rewrite the current page using JavaScript, allowing for a smoother, faster user experience.

React Router

HashRouter

We can use the URL to control which components are rendered by React. The URL becomes the single source of truth for what should be displayed on the screen.

The primary role of a router in a Single Page Application (SPA) is to manage page navigation without triggering a full page reload.

  • The router listens for changes in the browser’s URL. The router intercepts the change and decides which part of the application to render. For example, if the URL changes from /home to /about, the router will swap out the current component for a different one.
1
2
3
4
5
6
7
8
9
<HashRouter>
<div>
...
<Route path="/states" component={States} />
...
<Link to="/states">States</Link>
...
</div>
</HashRouter>
  • <HashRouter>: With HashRouter, the URL will contain a # symbol, followed by the client-side route. For example: http://localhost:3000/#/users/123. In this case, the URL before the hash (http://localhost:3000/) is what the server handles, and everything after the # (/users/123) is used by the client-side routing mechanism to render the appropriate view in the React app.
  • <Route />: Define a route in application. When the URL matches the path, React Router renders the component specified in the component prop. If the URL starts with the defined path, the route is considered a match.
  • <Link />: Generates a hyperlink with href=”#/states” and the text “States”.
  • In conclusion, when clicking the link with text “States”, the url will be updated to http://localhost:3000/p5.html#/states, where http://localhost:3000/p5.html is the current path, and the component States will be rendered by <Route path="/states" component={States} />. In a URL, the part after the # is called the fragment identifier or hash. The primary purpose of the hash in URLs is to provide a way to navigate to a specific section or state of a page without causing a full page reload.
  • When you load a URL with a hash (e.g., http://localhost:3000/#/users/123), the browser doesn’t send anything after the # to the server. It only requests the base URL (in this case, http://localhost:3000/). Then, hashRouter looks at the fragment (#/users/123) and maps it to the appropriate route defined in your React app (e.g., /users/:userId).

We can also pass parameters with React Router

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<Route
path="/Book/:book/ch/:chapter"
component={BookChapterComponent}
/>

function BookChapterComponent({ match }) {
return (
<div>
<h3>Book: {match.params.book}</h3>
<h3>Chapter: {match.params.chapter}</h3>
</div>
);
}

<Link to="/Book/Moby/ch/1">Moby</Link>
  • :book and :chapter are placeholders in the URL that will be dynamically replaced by actual values when the route is matched.
  • match is an object that contains information about how the URL matches the route.
  • When this link is clicked, the React Router will navigate to this URL, and the BookChapterComponent will render with match.params.book set to “Moby” and match.params.chapter set to “1”.
  • this.props.match is passed automatically to any component that is rendered by a Route.
  • If your component is supposed to receive props from React Router (like match, location, and history), it must be rendered inside a Route
    1
    2
    import { Route } from 'react-router-dom';
    <Route path="/users/:userId" component={YourComponent} />
  • Deep linking: Deep linking refers to the ability to link directly to a specific page or view within a web application. URLs that map directly to certain views (like /photos/57231f1a30e4351f4e9f4bd8) can be shared with others, who can then access the same page or state.

React Router provides two main ways to render components when a route matches: the component prop and the render prop.

  • component: This is used when you want to simply render a component without needing to pass additional props or logic.
  • render: This is used when you want to pass custom props or add additional logic before rendering the component. With render, you can control what props are passed to the component and include any dynamic data. render should be a function that returns the component.
1
<Route path="/users/:userId" render={props => <UserDetail {...props} extraProp={extraProp} handler={this.handleUserNameChange} />} />

Switch

Switch is responsible for rendering the first child <Route> that matches the current URL. It ensures that only one route is displayed at a time.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
let routes = (
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route path="/about">
<About />
</Route>
<Route path="/:user">
<User />
</Route>
<Route>
<NoMatch />
</Route>
</Switch>
);

Stanford CS142 笔记 - Single Page Application
https://thiefcat.github.io/2024/08/13/CS142/SPA/
Author
小贼猫
Posted on
August 13, 2024
Licensed under