react router v4 default page(not found page)

前端 未结 4 1131
生来不讨喜
生来不讨喜 2020-11-27 13:28

This is common purpose, directing unmatch request to notfound page.

making this with react-router v4 looks like previous versions and I expect this sample works bel

4条回答
  •  春和景丽
    2020-11-27 14:14

    Although the accept solution does provide the answer, but it wouldn't work when you have nested Routes

    For instance, if the Home component has nested Routes like /home, /dashboard and if the visited url is /db, it would show a NotFound component only within the Route section, but not the page as a whole.

    To avoid this, you can go along with a very simple tweak of using a component and a Provider

    const NoMatch = (props) => (
        
    )
    
    const ProviderHOC = (NotFoundRoute) => {
        const RouteProvider = (props) => {
            if(props.location && props.location.state && props.location.noMatch) {
               return  
            }
            return props.children;
        }
        return withRouter(RouteProvider)
    
    }
    
    export default ProviderHOC;
    

    And then you can use it like

    const RouteManager  = ProviderHOC(NotFoundComponent);
    
    
      
        
          
          
          
          
        
      
    
    

    and within Home component

    render() {
        return (
             
                   
                   
                   
             
        )
    }
    

提交回复
热议问题