代码之家  ›  专栏  ›  技术社区  ›  Mladen Skrbic

React路由器映射槽阵列

  •  1
  • Mladen Skrbic  · 技术社区  · 8 年前
        import React from 'react';
        import ReactDOM from 'react-dom';
        import { BrowserRouter  as Router, Switch, Route  } from "react-router-dom";   import Home from './components/Home';
        import About from './components/About';
        import Skills from './components/Skills';
    
        const titles=["About","Projects","Contact","Education","Skills","Resume"];
    
        ReactDOM.render(
            <Router>
                <Switch>
                  {
                    titles.map(title=>{
                    if(title==="Home"){return false;}
                    var path=title.toLowerCase();
                    console.log(title)
                    return (<Route exact path={"/"+path} component={title}/>)
                  })
                }
                  <Route exact path="/" component={Home}/>
                  <Route component={NotFound}/>
                </Switch>
          </Router>,document.getElementById('root'));
    <Route exact path="/" component={About}/>//if i put it like this it works(not in this place)
    

    我不知道为什么它不起作用,我尝试在映射数组后删除“”,但它也不起作用。

    1 回复  |  直到 8 年前
        1
  •  3
  •   Maxwelll    8 年前

    因为 const titles=["About","Projects","Contact","Education","Skills","Resume"]; 只是一个字符串数组,您将无法使用 component= 语法(因为这些是字符串而不是组件)。。。您可以轻松地将标题设置为对象数组

    const titles=[{name: "About", component: About...}];

    ... return (<Route exact path={"/"+title.name} component={title.component}/>)

    这将允许你保留你已经拥有的东西。

    推荐文章