【问题标题】:Nested Routing with url param is not working in react-router-dom带有 url 参数的嵌套路由在 react-router-dom 中不起作用
【发布时间】:2019-09-22 15:02:15
【问题描述】:

我正在 React-router-dom (v5.0.1) 中设置嵌套路由,但是当我尝试访问其中一个嵌套路由时,它(路由 /primary/:id)无法正常工作。

嵌套路由看起来像..

const id = ({match}) =>  (
    <div>
        with id {match.params.id}
    </div>
)

const primary = ({match}) => (
    <div>
        This is the Primary route
        <br/>
        <Link to='/primary/one'>Primary with id</Link>
        <Route path='/primary/:id' component={id} />
    </div>
)

我无法访问 id 组件。 我在 Routes 组件中调用主要组件。

const Routes = () => {
    return(
        <Router>
            <Route exact path='/' component={main} />
            <Route exact path='/primary' component={primary} />    
        </Router>
    )
}

RoutesApp组件中调用如下。

function App() {
  return (
    <div className="App">
      <Routes />
    </div>
  );
}

【问题讨论】:

    标签: reactjs react-router-dom


    【解决方案1】:

    primaryid 组件定义两个Routes,如下所示。

    
    const id = () =>  (
        <div>
            with id {props.id}
        </div>
    )
    
    const primary = () => (
        <div>
            This is the Primary route
            <br/>
            {
              props.match.params.id ? 
                <id id={props.match.params.id}/>
             : ""
            }
    
            <Link to='/primary/one'>Primary with id</Link>
        </div>
    )
    
    const Routes = () => {
        return(
            <Router>
                <Route exact path='/' component={main} /> 
                <Route exact path='/primary' component={primary} />
                <Route exact path='/primary/:id' component={id} />
            </Router>
        )
    }
    

    编辑 以下未经测试。试试这是否可行。

    const primary = ({match}) => (
        <div>
            This is the Primary route
            <br/>
            <Link to='/primary/one'>Primary with id</Link>
            {<Route path='/primary/:id' component={id} />}
        </div>
    )
    

    【讨论】:

    • 但我想要 ``` ``` 主组件内的这条路线.. 不可能.. ?
    • 您的意思是primary 组件作为每个id 组件的布局吗?
    • 由于 id 组件是从主要组件访问的,我希望该路由在主要组件中,而不是在 Routes 或 App 组件中。似乎在早期版本的 react-router-dom 上工作。我不知道为什么这现在不起作用。
    • 那不行..我想我必须声明没有路径的主路由.. ...现在它可以工作了..
    【解决方案2】:

    您只需将此代码放入您的路线中:

    const Routes = () => {
        return(
            <Router>
                <Route exact path='/' component={main} />
                <Route exact path='/primary/:id' component={primary} />    
            </Router>
        )
    }
    

    【讨论】:

      猜你喜欢
      • 2017-09-04
      • 1970-01-01
      • 2021-12-30
      • 2020-06-02
      • 2021-11-12
      • 2020-11-06
      • 2022-01-13
      • 2016-03-06
      • 1970-01-01
      相关资源
      最近更新 更多