服务器上的路由器响应位置不匹配

时间:2017-01-06 21:38:48

标签: react-router

我遵循此处给出的使用react路由器服务器端的示例:

https://github.com/ReactTraining/react-router/blob/v2.8.1/docs/guides/ServerRendering.md

以某种方式与这个简单的路由器设置匹配并不匹配给定的位置:

import React from "react"
import ReactDOMServer from 'react-dom/server'
import { Route, match, RouterContext, IndexRoute } from 'react-router'

const sampleRoutes = (
    <Route path="/">
        <IndexRoute component={() => <span>index</span>}/>
        <Route path="z1" component={() => <span>z1</span>} />
        <Route path="z2" component={() => <span>z2</span>} />
    </Route>
)

const render = location => {
    match({sampleRoutes, location}, (error, redirectLocation, renderProps) => {
        if (error) {
            console.error("error: "+ error)
        } else if (redirectLocation) {
            console.error("redirect to " + redirectLocation)
        } else if (renderProps) {
            var page = ReactDOMServer.renderToStaticMarkup(<RouterContext {...renderProps} />)
            console.log(page)
        } else {
            console.error("location nof found: '"+ location +"'")
        }
    })
}

render("/z1")

我得到&#34;未找到路线/ z1&#34;在控制台上。

1 个答案:

答案 0 :(得分:2)

match需要一个routes对象(它会将您的<Route>转换为对象,请参阅this comment),但是您提供了<Router>元素。尝试:

const sampleRoutes = (
  <Route path="/">
    <IndexRoute component={() => <span>index</span>}/>
    <Route path="z1" component={() => <span>z1</span>} />
    <Route path="z2" component={() => <span>z2</span>} />
  </Route>
)

其次,您将以下对象传递给match

{sampleRoutes, location}

转换为:

{ sampleRoutes: sampleRoutes, location: location }

当你真正想要的时候:

{ routes: sampleRoutes, location }
相关问题