【问题标题】:React Router Declared but doesn't work pleaseReact Router 已声明但无法正常工作
【发布时间】:2019-08-24 04:39:41
【问题描述】:

您好,我希望它在#/ 可以访问但#/ipb 可以访问时将InstrumentPage 渲染为没有道具,但当ipb 作为道具实体进行访问时。但它不起作用。

  render() {
    return (<React.Fragment>
      <HashRouter>
        <Switch>
          <Route path='/' render={(props) => <InstrumentPage {...props} />}/>
          {Object.keys(AppConfig).forEach((property) =>
            <Route path={property} render={(props) => <InstrumentPage {...props} entity={property} />} />)
          }
        </Switch>
      </HashRouter>
    </React.Fragment>);
  }

应用配置

const AppConfig = {
  pb: {
    header: 'PBHeader',
    body: 'PBBody',
  },
  ipb: {
    header: 'IPBHeader',
    body: 'IPBBody',
  },
};    
export default AppConfig;

【问题讨论】:

  • forEach 没有返回任何内容,您的意思是 map 在数组上吗?

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


【解决方案1】:

您需要使用map 并返回RouteforEach 除了undefined 不会返回任何内容。

<Switch>
    <Route exact path='/' render={(props) => <InstrumentPage {...props} />}/>
    {Object.keys(AppConfig).map((property) =>
      <Route 
        path={`/${property}`} 
        render={ (props) => <InstrumentPage {...props} entity={property} /> } 
      />
     )
    }
</Switch>

注意:当您写path={property} 时,表示path={ipb}path={pb} 是不正确的路径。正确的路径应该是path="/ipb"(注意斜线),为此您需要执行/${property} [包含反引号](使用Template string)。

还为您的第一个Route 添加exact 属性,否则它将匹配所有Routes

【讨论】:

    猜你喜欢
    • 2018-07-30
    • 1970-01-01
    • 2022-12-04
    • 2010-12-30
    • 2017-03-15
    • 2011-12-18
    • 2017-10-05
    • 2015-02-05
    • 2011-06-16
    相关资源
    最近更新 更多