- yarn remove react-router
-
- yarn add react-router-dom react-router
- const Routes = createBrowserRouter([......],{
- basename: '/app'
- })
改之前
- import B from './b'
-
- {
- path: '/a(/:id)',
- component: B,
- }
改之后, 同时不再支持可选路径 , 坑爹,很多人都说坑爹 V6: Optional parameters · Issue #7285 · remix-run/react-router · GitHub
- {
- path: 'a',
- element: <B/>,
- children: [{
- path: ':id',
- element: <B/>
- }]
- },
- componentDidMount() {
- this.routerChangeListener = this.context.router.listenBefore(this.beforeRouteChange);
- }
-
-
- componentWillUnmount() {
- this.routerChangeListener && this.routerChangeListener();
- }
-
- beforeRouteChange = () => {
- try {
- this.props.closeLightBox();
- } catch (error) {
- console.log('beforeRouteChange', error);
- }
- return true;
- };
更改为
- componentDidMount() {
- this.routerChangeListener = this.beforeRouteChange
- }
- shouldComponentUpdate(props) {
- if (props.location.search !== this.props.location.search) {
- this.routerChangeListener();
- }
- }
- componentWillUnmount() {
- this.routerChangeListener && this.routerChangeListener();
- }
-
- beforeRouteChange = () => {
- try {
- this.props.closeLightBox();
- } catch (error) {
- console.log('beforeRouteChange', error);
- }
- return true;
- };
- const rbRoutes = createBrowserRouter([
- {
- path: '/',
- element: <Layout onUpdate={onRouteUpdate } />,
- children: [...]
- }
- )
- componentDidUpdate() {
- this.props.onUpdate(this.props)
- }
location.query 不见了,需要自己处理
导航相关的,由于props不再有router对象,为了项目不进行大改,需要自己包装个方法
- import React from 'react';
- import {
- useLocation,
- useNavigate,
- useParams,
- useFormAction,
- } from "react-router-dom";
-
- import queryString from 'query-string';
-
- export function withRouter(Component) {
- function ComponentWithRouterProp(props) {
- let location = useLocation();
- let navigate = useNavigate();
- let params = useParams();
- const query = queryString.parse(location.search);
- const handleNavigate = (url, isReplace) => {
- let handleUrl = url;
- if (handleUrl[0] !== '/') {
- handleUrl = '/' + handleUrl;
- }
- navigate(handleUrl, { replace: isReplace });
- };
- const router = {
- push: (url) => handleNavigate(url),
- replace: (url) => handleNavigate(url, true),
- goBack: () => navigate(-1),
- location: { ...location, action: useFormAction() },
- query
- };
- return (
- <Component
- {...props}
- location={{ ...location, query }}
- navigate={navigate}
- params={params}
- router={router}
- />
- );
- }
-
- return ComponentWithRouterProp;
- }
-
- export function withRouterDom(Component) {
- const Node = withRouter(Component);
- return <Node />;
- }
- - import PropTypes from 'prop-types';
- + import { withRouter } from 'scripts/utils/RBWithRouter';
-
-
- - this.context.router.goBack();
- + this.props.router.goBack();
-
- - Index.contextTypes = {
- - router: PropTypes.object.isRequired
- - };
-
- - export default Index;
- + export default withRouter(Index);