2021-04-08 react-router-dom

router

  1. Route参数

        
        
    
         }
        >
        
    
        
        
    
         }
        >
        
    
        component 可以是类组件 不能是组件实例; 也可以是函数组件
        render渲染的组件,可以是函数组件, 不能是类组件, 在切换路由之后会卸载, 而children渲染的组件不会卸载, 只会调用一次
        children 不管路径是否匹配都会渲染 只能是函数组件 通过props.match可以判断当前组件是否是匹配的
    
  2. router相关

        import {
            BrowserRouter,
            Route,
            NavLink,
            Switch,
            withRouter,
            Redirect
        } from 'react-router-dom'
    
        // 给组件添加路由信息
        @withRouter
        class MyNavLink extends Component {
            render() {
                const pathname = this.props.location.pathname;
                this.props.history.push('/home');
    
                return 
    } } const Home = withRouter((props) =>
    Home
    ); render() { return <> } ```
  3. Redirect & 传参

        function loginPage() {
            const { state: { from } } = useLocation();
            const history = useHistory();
    
            function login() {
                // history.push(from);
                history.replace(from);
            }
    
            return 
    页面来自于: {from}
    } const PrivateRoute = ({ children, ...rest }) => { const { pathname } = useLocation(); return ( {isAuth ? children : } ) } ```
  4. 取参数

        // /about/:id
        // 
        // 
        // 
    
        const About = function() {
            const { id } = useParams();
            const { state: { id }, search } = useLocation();
            const query = new URLSearchParams(search);
            const sw = query.get('sw');
            return <>
                Params { id }
            
        }
        ```
    
    
  5. Page 404

        const Page404 = () => {
            return <>
                404 
            
        }
    
        
            
        
        ```
    
    
  6. Route Config

        
            {routes.map((item, index) => (
                }
                >
                
            ))}
        
        ```
    
    
  7. Children Config

        const routes = [
            { 
                path: '/a',
                component: Home
            },
            { 
                path: '/b',
                component: About,
                children: [
                    {
                        path: '/b1',
                        component: About1,
                    },
                    {
                        path: '/b2',
                        component: About2,
                    }
                ]
            },
        ]
    
        
    {route.map((item,index) => { let { path } = item; return ( ) }}
    function About(props) { const { routes } = props; return <> {routes.map(item => ( ))} } function RouteWithSubRoutes(props) { const { route } = props return ( ) } ```

你可能感兴趣的:(2021-04-08 react-router-dom)