使用 BrowserRouter 在 React JS 中使用字符串列表作为路径创建动态路由

Create dynamic route using list of string as paths in React JS with BrowserRouter

下面是我的路由器的当前实现,它有点硬编码和冗余。 我有一个包含所有路径的对象,例如下面的

path = ["physical-health","general-health","wellbeing"];

我想让它动态化以减少硬编码并使其更具可扩展性。 像这样。

for (var i = 0; i < path.length-1; i++) {
        <Route exact path={this.state.basePath + path[i]} render={() => <Welcome />} />
    } 

但它似乎无法在 BrowserRouter 中运行。

render() {
        return(
            <BrowserRouter history={history}>
                <div className="">
                    <div id="maincontent">
                        <Route exact path={this.state.basePath +"/physical-health"} render={() => <Welcome />} />
                        <Route exact path={this.state.basePath +"/general-health"} render={() => <Welcome />} />
                        <Route exact path={this.state.basePath +"/wellbeing"} render={() => <Welcome />} />
                    </div>
                </div>
            </BrowserRouter>
        );
    }

您可以使用 .map() 来完成您要查找的内容:

path = ["/physical-health","/general-health","/wellbeing"];
path.map(p => <Route exact path={this.state.basePath + p} render={() => <Welcome />} />)

另一种方式:

path = ["physical-health","general-health","wellbeing"];
path.map(p => <Route exact path={`${this.state.basePath}/${p}`} render={() => <Welcome />} />)

完整示例:

render() 
{
    const path = ["physical-health","general-health","wellbeing"];
    return(
        <BrowserRouter history={history}>
            <div className="">
                <div id="maincontent">
                    {path.map(p => <Route exact path={`${this.state.basePath}/${p}`} render={() => <Welcome />} />)}
                </div>
            </div>
        </BrowserRouter>
    );
}