使用react-router进行服务器端渲染

时间:2016-04-15 00:38:36

标签: javascript node.js reactjs react-router isomorphic-javascript

我试图通过最简单的Hello World示例来让react-router在服务器上运行,而且无论我做什么,回调中的道具总是未定义的。尝试两天后,似乎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,为什么会说&#34;找不到&#34;?根据文档和API,它应该像那样......我缺少什么?

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

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