你好,我希望它渲染 InstrumentPage
当 #/
时没有 Prop 是访问但是当 #/ipb
是访问通行证 ipb
作为 Prop 实体。但它不起作用。
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;
最佳答案
您需要使用map
并返回Route
,forEach
除了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}
[contains back-tick] (使用 Template string )。
还为您的第一个Route
添加exact
属性,否则它将匹配所有Routes
。
关于javascript - React Router 已声明但不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57635147/