如何始终初始化此reactjs组件的prop?

时间:2017-03-06 01:09:40

标签: reactjs react-router

我使用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组件是否有任何参数?

2 个答案:

答案 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>
    );
  }
}