Reactjs路由器匹配回调参数始终未定义

时间:2015-11-04 17:18:46

标签: javascript reactjs react-router

我使用match方法进行服务器端渲染,并且回调中的参数始终未定义。可能有些不对劲但是过了一整天我无法理解它。

这是我的服务器端渲染。

// Create location from the history module.
let location = createLocation(req.url);

match({Routes, location}, (error, redirectLocation, renderProps) => {

    // TODO : Verify why this is always undefined
    console.log('ERROR :: ', error)
    console.log('REDIRECT LOCATION :: ', redirectLocation)
    console.log('RENDER PROPS :: ', renderProps)

    if (redirectLocation) {
        res.redirect(redirectLocation.pathname + redirectLocation.search)
    }
    // TODO : Verify why this is breaking
    //else if (error || !renderProps) {
    //  return console.log('Error while starting server :: ', error)
    //}
    else {

        Transmit.renderToString(RoutingContext, renderProps).then(({reactString, reactData}) => {

            console.log('REACT STRING :: ', reactString);
            console.log('REACT DATA :: ', reactData);

            let output = (
                `<!doctype html>
                <html lang="en-us" style="min-height:100vh; width: 100%; background-color: #eee;">
                    <head>
                        <meta charset="utf-8">
                        <title>react-isomorphic-pandora-app</title>
                        <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">
                        <link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Roboto:400,100,700">
                    </head>
                    <body>
                        <div id="react-root">${reactString}</div>
                    </body>
                </html>`
            );

            var webserver = process.env.NODE_ENV === "production" ? "" : "//localhost:8080"

            output = Transmit.injectIntoMarkup(output, reactData, [`${webserver}/dist/client.js`])

            res.send(output)

        }).catch((error) => {

            res.send(error.stack).type("text/plain").code(500)

        })
    }
})

这是我的客户方。

import React from "react";
import ReactDOM from "react-dom";
import {Router} from "react-router";
import Transmit from "react-transmit";
import routes from "../views/Routes";
import {createHistory} from "history";

let reactRoot = window.document.getElementById("react-root");
let history = createHistory();
let location = history.createLocation();

const routerOption = {
    routes: routes,
    history: history,
    location: location
}

Transmit.render(Router, routerOption, reactRoot);

if (process.env.NODE_ENV !== "production") {
    if (!reactRoot.firstChild || !reactRoot.firstChild.attributes ||
        !reactRoot.firstChild.attributes["data-react-checksum"]) {
        console.error("Server-side React render was discarded. Make sure that your initial render does not contain any client-side code.");
    }
}

这是我的路线。

import React from "react"
import {Router, Route} from "react-router"
import MenuView from "./Menu"
import DefaultView from "./Default"
import AnotherView from "./Another"

export default (
    <Router component={MenuView}>
        <Route path="/" component={DefaultView} />
        <Route path="/another-view" component={AnotherView} />
    </Router>
);

任何帮助将不胜感激。 谢谢:))

编辑--------

这是我的MenuView组件中的代码。

class MenuView extends React.Component {

    constructor(){

        super()

        this.menuItems = [
            {
                type: MenuItem.Types.SUBHEADER,
                text: 'Menu sub header'
            },
            {
                route: '/',
                text: 'Home'
            },
            {
                route: '/another-view',
                text: 'Another view'
            }
        ]
    }

    childContextTypes = {
        muiTheme: React.PropTypes.object
    };

    getChildContext() {
        return {
            muiTheme: ThemeManager.getMuiTheme(DefaultTheme)
        }
    }

    _getSelectedIndex = () => {

        let currentItem;

        for (let i = this.menuItems.length - 1; i >= 0; i--) {
            currentItem = this.menuItems[i];
            if (currentItem.route && this.props.history.isActive(currentItem.route)) return i;
        }

    }

    _onLeftNavChange = (e, key, payload) => {

        this.props.history.pushState(null, payload.route);

    }

    render () {

        var style = {
            paddingTop: '92px'
        }

        return (
            <div>
                <LeftNav
                    ref="leftNav"
                    menuItems={this.menuItems}
                    onChange={this._onLeftNavChange}
                    selectedIndex={this._getSelectedIndex()}
                    style={style}/>
                <section className="content">
                    {this.props.children}
                </section>
            </div>
        )
    }

}

5 个答案:

答案 0 :(得分:4)

我猜你使用 babel 6 ,而不是 babel 5

我有类似的问题。 babel 5可以,但不适合babel 6。

经过长时间的调试,我发现进行以下更改可以解决我的问题。

变化:

 match({Routes, location}

为:

match({Routes.default, location}

答案 1 :(得分:4)

问题是路由文件中的exports default。它返回一个像{ defaults: { // routes in here }这样的对象,而在客户端上,它返回一个像{ // routes in here }这样的对象。您需要以modules.exports = [...routes...];

之类的其他方式导出文件

答案 2 :(得分:4)

由于Babel 5 vs. Babel 6和导出路径文件,它应该如下所示:

Babel 5:

  Router.match({ routes:routes, location: req.url}, etc ...

Babel 6:

  Router.match({ routes:routes.default, location: req.url}, etc ...

答案 3 :(得分:3)

你的es6解构分配错了。 Destructuring assignment

match({Routes, location})必须为match({routes, location})

或更安全的方式

match({routes:Routes, location:location})

答案 4 :(得分:0)

您的路线是问题所在。您有一个顶级<Router>,在RoutingContext之后您将match传递到<Router>。那是倒退,通常在客户端we create a RoutingContext within the <Router> component

我认为您只想让<Route>只是<MenuView>,以便在所有路线上提供您的顶级a组件。