【发布时间】:2015-09-12 18:05:28
【问题描述】:
我跟踪了examples 中的couple,试图从处理它的 React 组件中的 Route 访问参数。但是,当我希望它包含来自gamesView 路由的gameId 时,来自render 或componentDidMount 内部的this.props 上的console.log 的结果始终是{}。
client.js 启动路由器:
// 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 为简单起见删除了一些路由:
var routes = (
<Route name='home' path='/' handler={app}>
<DefaultRoute handler={home} location="/" />
<Route name='gamesView' path='/games/:gameId' handler={gamesView} />
</Route>
);
module.exports = routes;
...和包裹其他路线的app.js,我在RouteHandler 中尝试了使用和不使用{...this.props}。如果我从render 函数内部console.log(this.props) 也返回{}:
var App = React.createClass({
render: function() {
return (
<div className='container'>
<div className='row'>
<RouteHandler {...this.props} />
</div>
</div>
);
}
});
module.exports = App;
最后是 gamesView React 组件,我希望看到 props 对象。这里this.props也是{},下面的结果是错误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;
有人有什么想法吗?
【问题讨论】:
-
不应该是
<RouteHandler prop1={this.props.prop1} prop2={this.props.prop1} /> -
@pkurek 我相信我应该能够使用spread operator 而不必在 RouteHandler 中明确命名道具。
标签: javascript reactjs reactjs-flux react-router react-router-component