gpt4 book ai didi

javascript - React Router 已声明但不起作用

转载 作者:行者123 更新时间:2023-11-29 16:30:59 25 4
gpt4 key购买 nike

你好,我希望它渲染 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并返回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} [contains back-tick] (使用 Template string )。

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

关于javascript - React Router 已声明但不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57635147/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com