2017-08-30 57 views
0

我正在使用驗證的應用程序,使用react-router和react-router-redux來處理路由。當我從非私人路由開始時,我的路由得到了預期的呈現,當我直接在瀏覽器的地址欄中輸入私有路由的URL時,沒有任何東西被加載(截圖)。我該如何解決這個問題?在將私有組件的url輸入到瀏覽器的地址欄(React-router v4)時,頁面不會加載

PrivateRoute.js

const PrivateRoute = ({userStatus, component: Component, ...rest }) => { 

    const stuffToShow = (props) => { 
     if(userStatus.authenticated) { 
      return <Component {...props}/>; 
     } 
     return <Redirect to={{ 
      pathname: '/login', 
      state: { from: props.location } 
     }}/> 
    }; 

    return <Route exact {...rest} render={stuffToShow}/> 

}; 

export default connectComponent(['userStatus'], PrivateRoute); 

routes.js

export function renderRoutes(routes) { 
    return routes.map((route, i) => { 
     if(route.private) { 
      return <PrivateRoute key={i} {...route} />; 
     } 
     return <Route key={i} {...route}/>; 
    }) 
} 

const routes = [ 
    { 
     path: '/', 
     exact:true, 
     component: Home 
    }, 
    { 
     path: '/login', 
     exact:true, 
     component: Login 
    }, 
    { 
     path: '/registration', 
     exact:true, 
     component: Registration 
    }, 
    { 
     path: '/users/:id', 
     exact:true, 
     component: UserPage, 
     private: true 
    }, 
    { 
     path: '/users', 
     exact:true, 
     component: Users, 
     private: true 
    }, 
    { 
     path: '/goodBye', 
     exact:true, 
     component: Goodbye 
    }, 
    { 
     path: '*', 
     component: NoMatch 
    } 
]; 

根:

<Provider store={store}> 
     <Router history={history}> 
      <div> 
       <Header /> 
       <Switch> 
        {renderRoutes(routes)} 
       </Switch> 
      </div> 
     </Router> 
    </Provider> 

我怎樣把HTML Express服務器上:

 this.app.use('/api/users', userRoute); 
     this.app.use('/api/blogPosts', blogPostsRoute); 
     this.app.use('*',(req,res) => res.sendFile(path.resolve(__dirname, '..', 'public', 'index.html'))); 

enter image description here

回答

0

嘗試修改這一部分:

const stuffToShow = (props) => { 
    if(userStatus.authenticated) { 
     return <Component {...props}/>; 
    } 
    return (
     <Redirect to={{ 
     pathname: '/login', 
     state: { from: props.location } 
     }}/> 
    ); 
}; 

<Redirect />是多行,應與()封閉。這是我對你的問題的最好猜測。

+0

它與大括號的工作方式相同。我認爲這個問題最有可能出現在我的快遞服務器上,這與我如何呈現html有關。我將該部分添加到原始文章並更新了截圖。 – Umbrella

+0

我不認爲這是一個服務器問題,因爲我注意到您的控制檯中有錯誤。這意味着你的JavaScript有問題。嘗試修改'PrivateRoute'的返回值並且看它是否有效:'return {} />''' – Win

+0

仍然收到相同的錯誤。 – Umbrella

相關問題