容易忘記的騷操作
組件懶加載(動態(tài)引入組件)
需要用到babel的動態(tài)引入插件@babel/plugin-syntax-dynamic-import
承二,安裝之后蓄喇,webpack配置如下:
{
"presets": ["@babel/preset-react"],
"plugins": ["@babel/plugin-syntax-dynamic-import"]
}
然后安裝@loadable/component
附较,example:
import loadable from "@loadable/component";
import Loading from "./Loading.js";
const LoadableComponent = loadable(() => import("./Dashboard.js"), {
fallback: <Loading />
});
export default class LoadableDashboard extends React.Component {
render() {
return <LoadableComponent />;
}
}
匹配路由
useRouteMatch
// 注意用這種的話不能放在方法里面,只能放在FC里面
import { useRouteMatch } from "react-router-dom";
function BlogPost() {
let match = useRouteMatch("/blog/:slug");
// Do whatever you want with the match...
return <div />;
}
matchPath
import { matchPath } from "react-router";
const match = matchPath("/users/123", {
path: "/users/:id",
exact: true,
strict: false
});
<Prompt>
用于組件銷毀時觸發(fā)提醒智听,如:
<Prompt
when={formIsHalfFilledOut}
message="Are you sure you want to leave?"
/>
但是實(shí)際使用貌似只有離開當(dāng)前頁面到其他頁面會觸發(fā)恩敌,關(guān)閉頁面并不會提示,關(guān)閉頁面的提示需要如下操作
window.onbeforeunload = () => {
return '你想提示的信息'
}
也可以加上是否需要顯示的判斷
window.onbeforeunload = () => {
if (needRemind) {
return '你想提示的信息'
}
}
<Redirect>
如果在<Switch>
中使用<Redirect>
加from
屬性乔外,可以將from中所帶的參數(shù)床三,匹配傳入to中
如果不在<Switch>
中,則可以自定義一個組件來帶參重定向(暫時沒發(fā)現(xiàn)其他方法杨幼,有好辦法的還請不吝賜教)
import React from 'react'
import { Redirect, useParams, generatePath } from 'react-router'
interface Props {
to: string
}
const RedirectWithParam: React.FC<Props> = (props: Props) => {
let { to } = props
const params = useParams<{ [key: string]: string }>()
to = generatePath(to, params)
return <Redirect to={to} />
}
export default React.memo(RedirectWithParam)
如何通配路由
大部分場景應(yīng)用于路由匹配不上的情況撇簿,跳轉(zhuǎn)404或者主頁。
用react-router-config
時差购,由于沒有通配符*
了四瘫,可以將router.js/router.ts
改為router.jsx/router.tsx
后,直接在path: '/'
規(guī)則最后添加一條欲逃,代碼如下找蜜。
{
path: '/',
component: Layout,
routes: [
...
{
render: () => <Redirect to="404頁面路由" />,
},
],
},
直接使用<Switch><Route>
時,直接在最后面添加一條<Route>
即可稳析。
<Switch>
<Route path="/homepage" component={Homepage} />
<Route path="/subpage" component={Subpage} />
<Route component={404Page} />
</Switch>