【问题标题】:React router doesn't work correct with componentReact 路由器不适用于组件
【发布时间】:2019-02-02 11:02:24
【问题描述】:

如果路径匹配,我正在尝试渲染容器组件。

class MyTopComponent extends Component {
componentDidUpdate() {
    const params = getUrlParams(this.props.location);
    if (params.id && params.id !== this.props.id) {
        this.props.updateId(params.id);
    }
}
render() {
    const { a, b, c } = getUrlParams(this.props.location);
    return this.props.id && this.props.isDataReady ? (
    <div>
    <Switch>
        <Route path={MY_FIRST_PATH} component={MyContainer}/>
    </Switch>
    </div>
    ) : null;
}
}

问题是在转到路径后,然后返回,然后再次到路径,页面崩溃。 当我在组件中使用内联函数时它工作正常:

<Route path={MY_FIRST_PATH} component={() => <MyContainer/>}/>

第二种方式性能好吗?

【问题讨论】:

  • MY_FIRST_PATH 定义在哪里?
  • 这是一个常数

标签: reactjs react-router react-router-dom


【解决方案1】:

如果MY_FIRST_PATH 是一个常数,我认为它会解析为一个字符串,即'MY_FIRST_PATH',但在你的路径属性中你需要有path='/MY_FIRST_PATH'。你很可能忘记了你的/

【讨论】:

  • component={() => } 工作正常 component={MyContainer} 不起作用(转到路径后崩溃,返回,再次转到路径)
  • 你不能使用component={() =&gt; &lt;MyContainer/&gt;}。 prop 组件只能用于直接渲染组件,即component={MyContainer}。因此,对于内联函数,您应该使用 render={()=> }。尝试根据您的道具在您的路线内进行三元检查,例如:&lt;Route path='/MY_FIRST_PATH' render={()=&gt; propIsTrue ? &lt;MyContainer/&gt; : &lt;Redirect to='/' /&gt; } /&gt;
猜你喜欢
  • 2018-12-31
  • 1970-01-01
  • 2018-09-04
  • 2017-12-16
  • 2022-06-15
  • 1970-01-01
  • 2017-08-28
  • 2019-08-23
  • 1970-01-01
相关资源
最近更新 更多