1, React.lazy optimized routing
We found that our loading was much slower after adding routing, React.lazy can reduce the initial loading time of our application and improve the user experience, it is especially useful for large single page applications (SPA) or applications that need to optimize loading time
React.lazy
is a method provided by React for dynamically importing components, which serves to load components when they are needed, rather than loading all components when the application is initialized, thus improving the performance and loading speed of the application.
React.lazy
function accepts a function as an argument that dynamically imports the component. When the component needs to be rendered, React will call this function to load the component. Once loaded, the component will be cached for reuse in future renderings.
React.lazy
When used in conjunction with the Suspense
component, the loading state of dynamically loaded components can be handled elegantly, making the code clearer and easier to maintain.
Using lazy, optimize our router.tsx
const Home = lazy(() => import('@/pages/Home'));
const Login = lazy(() => import('@/pages/Login'));
const NotFind = lazy(() => import('@/pages/NotFind'));
2、Use Suspense
to load the effect by default
Versions prior to v6 use
// App.js
import React, { Suspense, lazy } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
const Login = lazy(() => import('./Login'));
const Admin = lazy(() => import('./Admin'));
const App = () => {
return (
<Router>
<Suspense fallback={<div>Loading...</div>}>
<Switch>
<Route exact path="/" component={Login} />
<Route path="/admin" component={Admin} />
</Switch>
</Suspense>
</Router>
);
};
export default App;
Some adjustments were made to this in v6
// App.js
import React, { Suspense, lazy } from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
const Login = lazy(() => import('./Login'));
const Admin = lazy(() => import('./Admin'));
const App = () => {
return (
<Router>
<Suspense fallback={<div>Loading...</div>}>
<Routes>
<Route path="/" element={<Login />} />
<Route path="/admin" element={<Admin />} />
</Routes>
</Suspense>
</Router>
);
};
export default App;
Refresh the page to see how we loaded
3、Nested routes Link and Outlet use
Next, we add two kinds of article types in the article, when you click on the jump to the corresponding interface, but the front of the Article still does not change the
First level page article Article.js
// Article.js
import React from 'react';
import { Link, Outlet } from 'react-router-dom';
const Article = () => {
return (
<div>
<h1>Article Page</h1>
<nav>
<Link to="Articletype1">Article Type 1</Link>{' '}
<Link to="Articletype2">Article Type 2</Link>
</nav>
<Outlet />
</div>
);
};
export default Article;
Article type page component (secondary routing)
ArticleType1.js
// ArticleType1.js
import React from 'react';
const ArticleType1 = () => {
return <div>Article Type 1 Page</div>;
};
export default ArticleType1;
ArticleType2.js
// ArticleType2.js
import React from 'react';
const ArticleType2 = () => {
return <div>Article Type 2 Page</div>;
};
export default ArticleType2;
Setting up routing
const ArticleType1 = lazy(() => import('@/views/article/Articletype1'));
const ArticleType2 = lazy(() => import('@/views/article/Articletype2'));
<Route path="/Article" element={<Article />}>
<Route path="Articletype1" element={<ArticleType1 />} />
<Route path="Articletype2" element={<ArticleType2 />} />
</Route>
Next we try to access Article:
It has been successfully realized!
4、Link change to programmatic routing way to jump
Previously, the jumps in our article were made using Link, but now we’ve rewritten them to be made using this programmatic routing approach
import { Link, Outlet,useNavigate} from 'react-router-dom';
<a href="#" onClick={(e)=>{tiao1(e)}}>Article Type 1</a>
const tiao1=(e:any)=>{
e.preventDefault();
navigate('/articletype1')
}
As a result, we clicked, strange, how to jump to 404?
Actually, our correct address should be '/article/articletype1'
Change it to try later:
const tiao1=(e:any)=>{
e.preventDefault();
navigate('/article/articletype1')
}
const tiao2=(e:any)=>{
e.preventDefault();
navigate('/article/articletype2')
}
The change of method was successful!
5, next in our background to achieve a management part of the secondary menu effect admin ( NavLink
and Link
)
The desired layout works roughly as follows:
Link:Link
is used to define navigational links, but does not provide style control. It is a simple wrapper for the HTML<a>
tag, used to make page jumps without refreshing the page.
NavLink:NavLink
is an enhanced version ofLink
that adds an active state to links matched by the current page, typically used to style navigation links to show the state of the current page or route. You can add custom class names or styles based on route matches.
If you need to add styling to a navigation link to reflect the current state of activity on the page or route, then it is recommended to use NavLink
.
Just need simple navigation links without active state style control, use Link
.
We used Link in our article, here we use NavLink for our menu.
That’s what we wrote before:
{/* NavLink */}
<NavLink to="/" activeClassName="active">Home</NavLink>
<NavLink to="/about" activeClassName="active">About</NavLink>
As a result, when writing in v6, it will report an error directly: Sure enough, the bastard changed the writing method in v6, and it is true that there is a pit in every step.
In v6 the routing was changed to the following:
let activeClassName = "underline"
<NavLink
to="/faq"
className={({ isActive }) =>
isActive ? activeClassName : undefined
}
>
FAQs
</NavLink>
Let’s look at our routing at the time of the match
6, refine our routing a bit:
javascript
import AntdComp from "./components/AntdComp";
import Header from "./components/Header";
import Login from "./views/Login";
import Register from "./views/Register";
import ForgetPassword from "./views/ForgetPassword";
import { Button, ConfigProvider, Space } from 'antd';
import NotFind from "./views/NotFind";
import Home from "./views/Home";
import User from "./views/subs/User";
import Role from "./views/subs/Role";
import { BrowserRouter, HashRouter, Routes, Route, Link, NavLink, Navigate } from "react-router-dom"
function App() {
return (
<ConfigProvider
theme={{
token: {
colorPrimary: '#7cb305'
},
}}
>
<BrowserRouter>
<ul>
<li>
<Link to="/register">sign up</Link>
</li>
<li>
<NavLink to="/forget">forgotten password</NavLink>
</li>
</ul>
<Routes>
<Route path="/" element={<Navigate to="/login"></Navigate>}></Route>
<Route path="/login" element={<Login></Login>}></Route>
<Route path="/home" element={<Home></Home>}>
<Route index element={<User></User>}></Route>
<Route path="role" element={<Role></Role>}></Route>
</Route>
<Route path="/register" element={<Register></Register>}></Route>
<Route path="/forget" element={<ForgetPassword></ForgetPassword>}></Route>
<Route path="/404" element={<NotFind></NotFind>}></Route>
<Route path="*" element={<Navigate to="/404"></Navigate>}></Route>
</Routes>
</BrowserRouter>
</ConfigProvider>
);
}
export default App;
Configure the route rendering exit under Home
import React from 'react'
import { Outlet, Link } from "react-router-dom"
export default function Home() {
return (
<div style={{ display: "flex" }}>
<div style={{ width: "200px", backgroundColor: "pink" }}>
<ul>
<li>
<Link to="/home/user">用户</Link>
</li>
<li>
<Link to="/home/role">角色</Link>
</li>
</ul>
</div>
<div>
<h3>content</h3>
<Outlet></Outlet>
</div>
</div>
)
}
Check our routing, perfectly implemented!