我使用react-router
来定义以下路线:
<Route
path="/plan"
components={App}
>
<Route
path="try/:planCategory"
components={PlanTrialContainer}
/>
<Route
path="pay/:planCategory"
components={PlanPurchaseContainer}
/>
</Route>
我们的想法是:当用户访问网址/plan
时,默认情况下他会看到计划概述,否则内容将由try/...
或pay/...
这是App
类
import React, { Component } from 'react';
import { Menu } from './Menu';
import PlansOverviewContainer from './PlansOverviewContainer';
export default class App extends Component {
render() {
const { children } = this.props.children;
let component = null;
if (children) {
component = children;
} else {
component = PlansOverviewContainer;
}
return (
<div>
<Menu />
{component}
</div>
);
}
}
当我尝试/plan
TypeError: Cannot read property 'children' of null
App.render
/Users/antkong/dev/myproject/plan/app/scripts/components/App.js
如果我从
更改行const { children } = this.props.children;
到
const children = this.props ? this.props.children : null;
它会起作用。
然而,我的首选版本是第一个版本,即无论如何都应初始化this.props
。如何确保初始化prop
?我可以使用的Router
组件是否有任何参数?
答案 0 :(得分:1)
您正在解构来自this.props.children
的孩子,这就像尝试:
this.props.children.children
而是将其更改为:
const { children } = this.props;
答案 1 :(得分:0)
你需要像这样调用超类初始化器:
import React, { Component } from 'react';
import { Menu } from './Menu';
import PlansOverviewContainer from './PlansOverviewContainer';
export default class App extends Component {
constructor(props) {
super(props);
}
render() {
const { children } = this.props.children;
let component = null;
if (children) {
component = children;
} else {
component = PlansOverviewContainer;
}
return (
<div>
<Menu />
{component}
</div>
);
}
}