Next vs. React's Router

Next vs. React's Router

Although Next is based on React, there are still big differences in some places, one of which is the difference in Router. The main reason is that React positions itself as a library (Library) , to be precise, a UI library - A JavaScript library for building user interfaces, so for the React development team, routing is not in their consideration. among.

In contrast, Next.js developed by vercel is positioned as a React framework that can be used for production - The React Framework for Production, and routing is naturally a must-have feature.

When using React directly for client side rendering , the implementation of routing is mostly implemented through the community-supported React Router DOM. The specific content is described in the basic application of React Router. The recommended configuration is as follows:

import {
    
     BrowserRouter as Router, Switch, Route } from "react-router-dom";

// 导入组件
import Home from "./components/Home";
import Blog from "./components/Blog";

const routes = () => (
  <Router>
    <Switch>
      {
    
    /* Switch 只会匹配第一个 URL 与 组件 匹配的内容,但是所有的路径都始于 / */}
      {
    
    /* 这里的关键字 exact 会匹配与 路径 完全一致的 URL */}
      <Route path={
    
    "/"} exact component={
    
    Home} />
      <Route path={
    
    "/home"} component={
    
    Home} />
      <Route path={
    
    "/blog"} component={
    
    Blog} />
    </Switch>
  </Router>
);

export default routes;

But the approach used by react-router-dom is an implementation called code based routing. Code based routing is still a relatively rare term, so I looked for it, mostly related to network coding. The technology that is often encountered in daily development is file based routing, which is the technology used by Next.js.

file based routing uses files as the entry, and Next.js uses the pagesfiles under the folder as the entry, such as:

index

index.js pagesas the entry file under the folder, you can your-domainopen it directly through.

pagesThe following can about.jsalso be your-domain/aboutopened by:

about

pages/day/index.jsIn the same way, you can your-domain/dayopen :

insert image description here

At this time, the internal implementation of Next.js is good, and there is no need for developers to do any configuration.

Guess you like

Origin blog.csdn.net/weixin_42938619/article/details/124144964