【问题标题】:react router on server doesn't match location服务器上的反应路由器与位置不匹配
【发布时间】:2017-05-21 18:03:57
【问题描述】:

我正在按照此处给出的示例使用反应路由器服务器端:

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")

我在控制台上收到“找不到路由 /z1”。

【问题讨论】:

    标签: react-router


    【解决方案1】:

    match 需要一个 routes 对象(它会将您的 &lt;Route&gt;s 转换为您的对象,请参阅 this comment),但您为它提供了一个 &lt;Router&gt; 元素。试试:

    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 }
    

    【讨论】:

    • 谢谢,我应用了您建议的 chage,但仍然得到“找不到路线”。我使用的是 react-router v2.8.1(粘贴了错误的链接)。我更新了我的问题以应用您的更改,因为看起来正确,即使仍然存在问题
    • 已更新以解决您的其他问题。
    猜你喜欢
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 2017-10-27
    • 2017-08-06
    • 1970-01-01
    • 2018-02-05
    • 1970-01-01
    相关资源
    最近更新 更多