怎么样在render一个react-router的时候传递参数

60次阅读

是这样,我写了个react应用。目前正在做后端渲染,
我的后端代码是这样的

 match({ routes, location: req.path }, (err, redirectLocation, props) => {
        if (err) {
            res.status(500).send(err.message);
        } else if (redirectLocation) {
            res.redirect(302, redirectLocation.pathname + redirectLocation.search);
        } else if (props) {
            getInitState(req,(err,state)=>{
                if(err) {
                    res.sendStatus(404);
                } else {
                    props.location.state = state;
                }
                const markup = renderToString(
                    <RoutingContext {...props}/>
                );
                res.render('index', {markup:markup,state:state});
            });
        } else {
            console.log("404");
            res.sendStatus(404);
        }
    });

我这里直接把数据放在了props.location.state上面了,
,然后在模板里面将这个数据挂载到全局location上

<script>
    location.state = '<%- JSON.stringify(state) %>';
    location.state = JSON.parse(location.state);
</script>

我希望这个location做为参数传递给router,使得前后端数据一致。

于是

React.render (
    Routers(location.state),
    document.getElementById('react-main')
);

我的Routers是这样的


module.exports = function Routers(props) {
    return (
        <Router history = {browserHistory} state = {props}>
            <Route path="/" component = {App}>
                <Route path="/home" component = {Article}/>
                <Route path = "/article/write" component = {WriteArticle}/>
                <Route path = "/article/edit/:id" component = {WriteArticle}/>
                <Route path = "/article/:id" component = {ArticleDetail}/>
                <Route path = "/category" component = {Category}>
                    <Route path = "/category/:id" component = {CategoryDetail}/>
                </Route>
                <Route path = "/about" component = {About}/>
                <Route path = "/tags" component = {Tags}>
                    <Route path = "/tags/:id" component = {TagsDetail}/>
                </Route>
                <Route path = "/login"  component = {Login}/>
                <Route path = "/admin/cate"  component = {AdminCate}/>
                <Route path = "/admin/tags"  component = {AdminTags}/>
                <Route path = "/admin/article"  component = {AdminArticle}/>
                <Route path="/*" component = {NoMatch}/>
            </Route>
        </Router>
    )
};

显然这样传递参数是有问题的,
请问一下如何传递一个location给router组件呢

Cocbin

正文完