当运行babel-node server.js时一切正常,但是当我创建一个构建并用babel转换我的es6代码时,匹配函数找不到匹配,我总是返回404错误消息。我在我的Isomorphic / Universal服务器上使用它。
当我在console.log中时,ES6版本和转换版本中的值看起来是一样的。
我的server.js中的实际ES6匹配代码
let history = useRouterHistory(useQueries(createMemoryHistory))()
let routes = createRoutes(history)
let location = history.createLocation(req.url)
match({ all_routes, location }, (error, redirectLocation, renderProps) => {
if (redirectLocation) {
res.redirect(301, redirectLocation.pathname + redirectLocation.search)
} else if (error) {
res.status(500).send(error.message)
} else if (renderProps == null) {
res.status(404).send('Not found')
} else {
我的.babelrc看起来像这样:
{
"presets": ["es2015", 'stage-2',"react"],
"plugins": [ "transform-object-rest-spread","transform-react-jsx"]
}
我的路线档案:
const routes = function(){
return (
<Router history={browserHistory}>
<Route path="/" component={App}>
<IndexRoute component={Home} />
<Route path="contact" component={Contact} />
<Route path="login" component={Login} />
<Route path="*" component={NotFound} />
</Route>
</Router>
)
}
当我在console.log路由时,它看起来像这样:
{ '$$typeof': Symbol(react.element),
type:
{ [Function]
displayName: 'Route',
createRouteFromReactElement: [Function: createRouteFromReactElement],
propTypes:
{ path: [Object],
component: [Object],
components: [Object],
getComponent: [Object],
getComponents: [Object] } },
key: null,
ref: null,
props:
{ path: '/',
component: { [Function] displayName: 'App' },
children:
[ [Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object] ] },
_owner: null,
_store: {} }
答案 0 :(得分:1)
createRoutes
需要一个routes
对象,但您传递的是history
个实例。您需要以允许您在服务器上导入<Route>
函数的方式从routes
函数中提取// routes.js
export const routes = (
<Route path="/" component={App}>
<IndexRoute component={Home} />
<Route path="contact" component={Contact} />
<Route path="login" component={Login} />
<Route path="*" component={NotFound} />
</Route>
)
。
import { routes } from './routes'
function router() {
return (
<Router history={browserHistor}>
{routes}
</Router>
)
}
然后您将路由器定义为:
createRoutes
在服务器上,您可以导入路线,然后将它们传递给match
(尽管如果您不这样做,import { routes } from './routes'
function handler(req, res) {
match({ routes, req.url }), function(...) {
// ...
})
}
会为您执行此操作。)
{{1}}