Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/google-maps/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何始终初始化此组件的道具?_Reactjs_React Router - Fatal编程技术网

Reactjs 如何始终初始化此组件的道具?

Reactjs 如何始终初始化此组件的道具?,reactjs,react-router,Reactjs,React Router,我使用react router定义了以下路由: <Route path="/plan" components={App} > <Route path="try/:planCategory" components={PlanTrialContainer} /> <Route path="pay/:planCategory" components={PlanPurchaseContainer} /> <

我使用
react router
定义了以下路由:

<Route
  path="/plan"
  components={App}
>
  <Route
    path="try/:planCategory"
    components={PlanTrialContainer}
  />
  <Route
    path="pay/:planCategory"
    components={PlanPurchaseContainer}
  />
</Route>
当我尝试
/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;

它会起作用的


但是,我的首选版本是第一个版本,即
此。无论发生什么情况,都应初始化道具。如何确保
prop
已初始化?是否有我可以使用的
路由器
组件的任何参数?

您需要调用超级类初始值设定项,如下所示:

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>
    );
  }
}
import React,{Component}来自'React';
从“./Menu”导入{Menu};
从“/plansovervewcontainer”导入plansovervewcontainer;
导出默认类应用程序扩展组件{
建造师(道具){
超级(道具);
}
render(){
const{children}=this.props.children;
让component=null;
if(儿童){
组件=儿童;
}否则{
组件=PlansOverviewContainer;
}
返回(
{component}
);
}
}

您正在从
此.props.children
解构子项,这与尝试执行以下操作类似:
this.props.children.children

改为:


const{children}=this.props

添加构造函数不会改变任何内容。看看我的答案。
const children = this.props ? this.props.children : null;
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>
    );
  }
}