阅读堆栈溢出和互联网后,我找不到似乎很容易解决的问题的解决方案,但是......我无法解决。
问题很简单,<Route path={
${match.path}/notas } component={Dashboard} />
不渲染 Dashboard
组件...为什么?不知道。
这是通用代码:
索引,路由开始的地方:
const rootNode = document.getElementById('root')
ReactDOM.render(
<Provider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>,
rootNode
)
App 组件,主要布局:
class App extends Component {
componentWillMount() {
const data = { loggedIn: false }
sessionStorage.setItem('auth', JSON.stringify(data))
}
render() {
return (
<section>
<Helmet>
<meta charSet="utf-8" />
<title>{APP_TITLE}</title>
</Helmet>
<Switch>
<Route path="/" exact component={Login} />
<ProtectedRoute path="/home" exact component={Home} />
</Switch>
</section>
)
}
}
和主页组件:
const Home = ({match}) => {
return <section className="home--grid">
<Sidebar />
<div className="home--grid">
<Switch>
<Route path={`${match.path}`} exact component={Dashboard} />
<Route path={`${match.path}/videos`} component={Dashboard} />
<Route path={`${match.path}/notas`} component={Dashboard} />
<Redirect to={`${match.url}`} />
</Switch>
</div>
</section>
}
就这么简单吗,没什么特别的……想法是Dashboard
会根据match.path
显示一些json内容,但是当我导航到已建立的路径时,该应用程序不显示任何内容,只是一个空白 <section>
,不知道为什么...
快速说明:Home
的第一次渲染完美呈现边栏和 Dashboard
与第一条路线有关。
这是到达组件的导航:
const Sidebar = () => {
return <nav className="home--sidenav">
<ul className="sidenav--items">
<li>
<NavLink to="/home">Total</NavLink>
</li>
<li>
<NavLink to="/home/videos">Videos</NavLink>
</li>
<li>
<NavLink to="/home/notas">Notas</NavLink>
</li>
</ul>
</nav>
}
编辑 通过请求,仪表板组件:
import React, { Component } from 'react'
import { connect } from 'react-redux'
class Dashboard extends Component {
render() {
return (
<div>
{this.props.match.path}
</div>
)
}
}
const mapStateToProps = state => ({ dashboard: state.dashboard })
export default connect(mapStateToProps)(Dashboard)
是的,现在就这么简单......
更新
我一直在试验,我的第一个想法是“更新拦截器”,但文档中的任何可能的修复都不起作用,包装 Dashboard
组件变成 withRouter
功能如:
const WrappedDash = withRouter(Dashboard)
并将其传递到路由中,尝试使用
渲染子组件 render={() => <Dashboard />}
也不显式传递 location
在 render 方法中将对象传递给 Dashboard。
每种情况都是一样的,NavLink 将我带到指示的路线,但它什么也不呈现(一个空的部分元素)。
奇怪的是,即使我做了一条像 /videos
这样的普通路线相反 ${match}/videos
,路由器不渲染任何东西。我认为这可能是经过身份验证的路由的问题,但对我来说没有任何意义。
最佳答案
应用内
<Switch>
<ProtectedRoute path="/home" exact render={ () => <Home/>} />
<Route path="/" exact render={ () => <Login/>} />
</Switch>
在家里
<Switch>
<Route path={`${match.path}`} exact render={ () => <Dashboard/>} />
<Route path={`${match.path}/videos`} render={ () => <Dashboard/>} />
<Route path={`${match.path}/notas`} render={() => <Dashboard/>} />
<Redirect to={`${match.url}`} />
</Switch>
需要使用 render 属性。
关于javascript - React router v4 Route 不显示组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49327635/