已声明React Router,但无法正常工作

use*_*230 2 javascript reactjs react-router react-router-dom

您好,我希望它InstrumentPage#/访问时以无道具的形式呈现,但在#/ipb访问通过时ipb作为props实体。但这不起作用。

  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>);
  }
Run Code Online (Sandbox Code Playgroud)

AppConfig

const AppConfig = {
  pb: {
    header: 'PBHeader',
    body: 'PBBody',
  },
  ipb: {
    header: 'IPBHeader',
    body: 'IPBBody',
  },
};    
export default AppConfig;
Run Code Online (Sandbox Code Playgroud)

rav*_*l91 5

您需要使用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>
Run Code Online (Sandbox Code Playgroud)

注意:当您写path={property}哪个意味着path={ipb}path={pb} 哪个不正确的路径时。正确的路径应该是path="/ipb"(请注意斜杠),为此,您需要执行/${property}[包含反选](使用Template string)。

还要exact为您的第一个添加道具,Route否则它将与所有道具匹配Routes