Hellou。目前,我正在尝试将create react app移至Gatsby。在CRA中,我以这种方式声明了自己的路线。
routes.js
/* eslint-disable react/no-multi-comp */
/* eslint-disable react/display-name */
import React, { lazy } from 'react'
import { Redirect } from '@reach/router'
import MainLayout from './layouts/MainLayout'
import LandingPage from './containers/LandingPage'
const routes = [
{
route: '*',
component: MainLayout,
routes: [
{
path: '/',
exact: true,
component: LandingPage,
},
{
path: '/login',
exact: true,
component: lazy(() => import('./containers/Login')),
},
{
path: '/register',
exact: true,
component: lazy(() => import('./containers/Register')),
},
{
path: '/password/reset',
exact: true,
component: lazy(() => import('./containers/PasswordReset')),
},
{
path: '/password/token/:token',
exact: true,
component: lazy(() => import('./containers/PasswordReset')),
},
{
path: '/password/request/:status',
exact: true,
component: lazy(() => import('./containers/Confirmation')),
},
{
path: 'email/confirmation',
exact: true,
component: lazy(() => import('./containers/Confirmation')),
},
{
path: '/blog',
exact: true,
component: lazy(() => import('./containers/Blog/Home')),
},
{
component: () => <Redirect to="/errors/error-404" />,
},
],
},
]
export default routes
这是我的app.js文件
import React from 'react';
import { Router } from '@reach/router'
import { Provider } from 'react-redux';
import CookiesProvider from 'react-cookie/cjs/CookiesProvider'
import { Cookies } from 'react-cookie'
import jwt_decode from 'jwt-decode';
import { setAuthToken } from '../services';
import { setCurrentUser, logoutUser } from '../store/actions/authActions';
import store from '../store/store'
import Alert from '../components/Alert'
import { H_JWT_COOKIE } from '../constants/constants';
import { renderRoutes } from 'react-router-config';
import routes from '../routes'
// Check for token
const cookie = new Cookies()
if(cookie.get(H_JWT_COOKIE)) {
// Set AuthToken
setAuthToken(cookie.get(H_JWT_COOKIE));
// Decode token and get user info and expiration
const decoded = jwt_decode(cookie.get(H_JWT_COOKIE));
// Set user and isAuthenticated
store.dispatch(setCurrentUser(decoded));
// Chek for expired token
const currentTime = Date.now() / 1000
if(decoded.exo < currentTime) {
store.dispatch(logoutUser());
window.location.href = '/login';
}
}
const App = () => {
return (
<CookiesProvider>
<Provider store ={store}>
<Router >
<Alert />
{renderRoutes(routes)}
</Router>
</Provider>
</CookiesProvider>
);
};
export default App
是否有任何教程以类似方式处理Gatby中的路由? 我希望能够创建动态网址。我可以在Gatsby中使用此react-router-config吗? 我正在尝试在gatsby-node.js中使用renderRoutes,但是没有成功。
答案 0 :(得分:0)
如果您使用这样的客户端呈现方法,您将不会从Gatsby中获得太多收益。解决身份验证后,请考虑使用骨骼渲染页面并更新道具。至少通过这种方式,可以预先静态呈现公共内容和您的基本HTML文档。您还希望切换到使用webpack逐页处理导入(不进行动态导入),让Gatsby协调默认的“到达路由器”设置。