【问题标题】:React-Router Route from child Switch does not render component来自子 Switch 的 React-Router Route 不渲染组件
【发布时间】:2021-03-21 02:31:35
【问题描述】:

我在这里阅读了多个线程,Switch 组件可以毫无问题地存在于多个文件中。但是,我在不同组件中的 Route 不会呈现其内容。

情况如下:

HOC 内容组件

// I have a useHistory() variable exported from an external file, that variable is named history
onComplete = () => {
  history.push('/home')
}

// Consider that onComplete() is called properly and works.

return(
 <>
    <Switch>
       <Route exact path='/home' component={Home}  // Also tried with render props...
    </Switch>
 </>
)

首页组件

useEffect(() => {
  history.push('/search')
}, [])

return(
 <>
    <Switch>
       <Route exact path='/search' component={Search}  // Also tried with render props...
    </Switch>
 </>
)

搜索组件

useEffect(() => {
  // This does not print, it does not reach.
  console.log('hey')
}, [])

return(
 <>
    <h1>Search component</h1>
 </>
)

我设法到达 Home 组件,并打印了 useEffect 挂钩中的 console.log(..)。然后发生路由更改,我的浏览器在地址栏中显示 localhost:3001/search,但屏幕上没有呈现任何内容。

如果我将 Search 组件放在 Content 组件的 Switch 中的 Route 中,则组件会被渲染, 有什么想法吗?

谢谢!

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

    搜索路径将是 /home/search .. 因为嵌套开关。 尝试打开

    localhost:3001/home/search
    

    【讨论】:

    • 恐怕它似乎无法解决问题。路径与 /home/search 一样好,但组件仍然无法呈现。
    猜你喜欢
    • 1970-01-01
    • 2016-11-05
    • 1970-01-01
    • 2018-08-11
    • 2018-09-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多