簡體   English   中英

使用React-Router進行服務器端渲染

[英]Server side rendering with react-router

我正在嘗試使用最簡單的Hello World示例在服務器上運行react-router,無論我做什么,回調中的props始終是未定義的。 經過兩天的嘗試,API似乎已經發生了巨大變化,我找到的所有答案都與舊API有關。

因此,這里是超級簡單的代碼示例:

import http from 'http'
import React from 'react'
import { renderToString } from 'react-dom/server'
import { match, RoutingContext } from 'react-router'
import fs from 'fs'


class Home extends React.Component{
    render(){
        return <div>{this.props.children}</div>         
    }
}

class Hello extends React.Component{
    render(){
        return <h1>Hello World</h1>
    }
}

class Routes extends React.Component{
    render(){
        return (
            <Route path="/" component={Home}>
                <Route path="hello" component={Hello} />
            </Route>
        )
    }
}

http.createServer((req, res) => {

    match({ Routes, location: req.url }, (err, redirect, props) => {
        if (props){
            let markup = renderToString(<RouterContext {...props}/>)
            res.write(markup)
            res.end()
        } else {
            res.write("not found")
            res.end()
        }

    })  
}).listen(8888);

如果在瀏覽器中輸入/ hello,為什么顯示“未找到”? 根據文檔和API,它應該像那樣工作..我缺少什么?

謝謝你的幫助!

Interrobang給了我正確的提示,我設法使它起作用,如果有人感興趣,請在這里運行示例:

import http from 'http'
import React from 'react'
import { renderToString } from 'react-dom/server'
import { Route, match, RouterContext } from 'react-router'
import fs from 'fs'


class Home extends React.Component{
    render(){
        return <div>{this.props.children}</div>         
    }
}

class Hello extends React.Component{
    render(){
        return <h1>Hello World</h1>
    }
}

const routes = (
    <Route path="/" component={Home}>
        <Route path="hello" component={Hello} />
    </Route>    
)

http.createServer((req, res) => {

    match({ routes, location: req.url }, (err, redirect, props) => {
        if (props){
            let markup = renderToString(<RouterContext {...props}/>)
            res.write(markup)
            res.end()
        } else {
            res.write("not found")
            res.end()
        }

    })  
}).listen(8888);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM