2

I've followed a couple of examples in an attempt to get access to a parameter from a Route in the React component that handles it. However the result of console.log on this.props from inside the render or componentDidMount is always {} when I'd expect it to contain the gameId from the gamesView route.

client.js which starts the Router:

// HTML5 History API fix for local 
if (config.environment === 'dev') {
    var router = Router.create({ routes: routes });
} else {
    var router = Router.create({ routes: routes, location: Router.HistoryLocation });
}

router.run(function(Handler) {
    React.render(
        <Handler />,
        document.getElementById('app')
    );
});

routes.js with some routes removed for simplicity:

var routes = (
    <Route name='home' path='/' handler={app}>
        <DefaultRoute handler={home} location="/" />
        <Route name='gamesView' path='/games/:gameId' handler={gamesView} />
    </Route>
);

module.exports = routes;

...and app.js which wraps the other routes, I've tried it both with and without {...this.props} in the RouteHandler. If I console.log(this.props) from inside the render function here is also returns {}:

var App = React.createClass({
    render: function() {
        return (
            <div className='container'>
                <div className='row'>
                    <RouteHandler {...this.props} />
                </div>
            </div>
        );
    }
});

module.exports = App;

Finally the gamesView React component that I expect to see the props object. Here this.props is also {} and the following results in the error TypeError: $__0 is undefined var $__0= this.props.params,gameId=$__0.gameId;:

var GamesView = React.createClass({
    render: function() {
        var { gameId } = this.props.params;

        return (
            <div>
                <h1>Game Name</h1>
                <p>{gameId}</p>
            </div>
        );
    }
});

module.exports = GamesView;

Anybody have any ideas?

4

2 回答 2

0

在您位于路由器中定义的组件之前,您不会看到这些参数。App对他们一无所知。但是,如果您将其console.log(this.props.params)放入gamesView组件中,您应该会看到它们。

于 2015-06-26T05:29:57.860 回答
0

讨论了 React Router (RR) Github之后发现这是因为我使用的是旧版本的 RR (v0.11.6)。

查看该版本的文档中的示例,它表明我需要使用Router.Statemixin,然后通过var gameId = this.getParams().gameId;.

在不升级 RR 的情况下,我的原始示例的工作版本GamesView变为:

var React = require('react');
var Router = require('react-router');
var { Route, RouteHandler, Link } = Router;

var GamesView = React.createClass({

    mixins: [ Router.State ],

    render: function() {
        var gameId = this.getParams().gameId;

        return (
            <div>
                <h1>Game Name</h1>
                <p>{gameId}</p>
            </div>
        );
    }
});

module.exports = GamesView;
于 2015-06-27T15:19:54.903 回答