我有一个使用 React、Redux 和 React-Router 1.0.0-rc1 的小型原型(prototype)。原型(prototype)使用Webpack进行代码分割。目前,它使用 getComponents 和 getChildRoutes 来异步加载其他路由,如下所示:
module.exports = {
path: 'donations',
getChildRoutes(location, cb) {
require.ensure([], (require) => {
cb(null, [
require('./routes/Donation'),
]);
});
},
getComponent(location, cb) {
require.ensure([], (require) => {
cb(null, require('./components/Donations'));
});
}
};
这个工作正常,直到我点击嵌套路由donations/:id,它看起来像:
module.exports = {
path: ':id',
getComponents (location, cb) {
console.log('got it', cb); // debugging
require.ensure([], (require) => {
console.log('called it', cb); // debugging
cb(null, require('./components/Donation'));
});
}
};
当我导航到此路线(例如:/donations/123)时,该路线将被触发,bundle.js 文件将被加载,并且 console.log s 出现在控制台中,所以我知道该路线已加载到内存中。 但是,该组件未安装和渲染。
console.log结果:
got it function (error, value) {
done(index, error, value);
}
called it function (error, value) {
done(index, error, value);
}
异步路由深一层是可以的,但是嵌套过去是行不通的。组件已加载,但看起来并未执行。
返回的组件用 Redux 的 Connect 包装,如下所示:
function Connect(props, context) {
_classCallCheck(this, Connect);
_Component.call(this, props, context);
this.version = version;
this.store = props.store || c…
更新:问题已解决
问题很简单。由于这是一个嵌套路由,因此 Router 将嵌套组件传递给 this.props.children 中的父组件,而我没有检查这一点。将其归因于对 1.0.0-rc1 的(稀疏)文档的误解。
请您参考如下方法:
我对react-router有一个根本性的误解有效,因为当您使用嵌套(子)路由时,父组件需要将它们容纳为 this.props.children :
之前
render() {
let { DonationsComponent } = this.props
return (
<div>
<h2>Donations</h2>
<DonationsList donations={DonationsComponent} entities={entities} />
</div>
);
}
在上面,render不考虑this.props.children ,因此嵌套路由(捐赠)被拉入并连接,但未渲染。
render() {
let { children, DonationsComponent, entities } = this.props
let child = <DonationsList donations={DonationsComponent} entities={entities} />
return (
<div>
<h2>Donations</h2>
{children || child}
</div>
);
}
现在,当 react-router拉入嵌套路由并将其传递给 this.props.children ,render函数执行正确的操作并呈现 children而不是child .






