问题描述
尝试执行以下操作,但不起作用.
ReactDOM.render(<路由器><div className="路由包装器"><开关><应用程序><路由精确路径="/" component={HomePage}/><Route path="/user" component={UserPage}/></应用程序><路由组件={Err404}/></开关>
尝试执行以下操作,但不起作用.
ReactDOM.render(<路由器><div className="路由包装器"><开关><应用程序><路由精确路径="/" component={HomePage}/><Route path="/user" component={UserPage}/></应用程序><路由组件={Err404}/></开关>
</路由器>,document.getElementById('main'))
正如文档所说,在 Switch 元素中只允许使用 Route 和 Redirect 元素.如何在不将 HomePage 和 UserPage 显式包装在 App 中或让 App 包装错误页面的情况下使其正常工作?
虽然我已经开始开发通用 React 应用程序",其中第一页加载是通过服务器端渲染完成的,但我遇到了与 React 类似的问题-路由器刚刚更新到4.0.您应该考虑按照以下方式重构您的应用程序:
ReactDOM.render(<路由器><div className="路由包装器"><开关><Route path="/" component={App}/><路由组件={Err404}/></开关>
</路由器>,document.getElementById('main'))
App 组件重构如下:
class App 扩展 React.Component {使成为() {返回 <开关><路由精确路径="/" component={HomePage}/><路由精确路径="/user" component={UserPage}/></开关>;}}
Trying to do the following, but it's not working.
ReactDOM.render(
<Router>
<div className="route-wrapper">
<Switch>
<App>
<Route exact path="/" component={HomePage} />
<Route path="/user" component={UserPage} />
</App>
<Route component={Err404} />
</Switch>
</div>
</Router>,
document.getElementById('main')
)
As the documentation says only Route and Redirect elements are allowed inside a Switch element. How do I get this to work without explicitly wrapping HomePage and UserPage in App or having the error page wrapped by App?
While I have begun developing a "Universal React app", where the first page load is done with server-side rendering, I faced similar problem as the React-Router had just updated to 4.0. You should consider restructuring you application something as given below:
ReactDOM.render(
<Router>
<div className="route-wrapper">
<Switch>
<Route path="/" component={App} />
<Route component={Err404} />
</Switch>
</div>
</Router>,
document.getElementById('main')
)
Where the App component is refactored as following:
class App extends React.Component {
render() {
return <div>
<Switch>
<Route exact path="/" component={HomePage} />
<Route exact path="/user" component={UserPage} />
</Switch>
</div>;
}
}
这篇关于React Router v4 嵌套路由与 Switch的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!