gpt4 book ai didi

reactjs - React-Router 嵌套路由加载空白页面而不是在父组件内部加载

转载 作者:行者123 更新时间:2023-12-04 12:44:50 25 4
gpt4 key购买 nike

我是 React 的新手,正在尝试创建带有嵌套路由的布局。这是我的场景

  • 当 URL 为/时显示登录
  • 当 URL 为/dashboard 时显示 Dashboard
  • 当 URL 为/dashboard/profile 时显示配置文件(这应该加载在仪表板内容区域内)

当在浏览器中访问 URL 时,登录页面和仪表板页面会正确加载,但对于/dashboard/profile,浏览器会转到空白页面,而不是将其加载到仪表板组件中。

索引.js

ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById('root'));

App.js

class App extends Component {
render() {
return (
<div>
{/* <Switch> */}
<Route exact path='/' component={SignIn}/>
<Route exact path='/dashboard' component={Dashboard}/>
{/* </Switch> */}
</div>
);
}
}

export default App;

Dashboard.js

class Dashboard extends React.Component {

render() {
const { classes } = this.props;

return (
<React.Fragment>
<CssBaseline />
<div className={classes.root}>
<Header classes={classes} open={this.state.open} click={this.handleDrawerOpen} />
<Sidebar classes={classes} open={this.state.open} click={this.handleDrawerClose} />
<main className={classes.content}>
<div className={classes.appBarSpacer} />

*********I expect profile component to load here
but when I access the URL /dashboard/profile I get a new blank page*********

Route path="/dashboard/profile" exact component={Profile} />



</main>
</div>
</React.Fragment>
);
}
}

最佳答案

在执行子路由时,您需要从 Dashboard 路由(存在于 Switch)中删除 exact 属性。

这是您的用例的最小实现:

import React, { Component } from "react";
import "./styles.css";

import {
NavLink,
Redirect,
Route,
BrowserRouter as Router,
Switch
} from "react-router-dom";

const App = () => (
<Router>
<div className="App">
<ul>
<li>
<NavLink to="/login">Login</NavLink>
</li>
<li>
<NavLink to="/dashboard">Dashboard</NavLink>
</li>
</ul>

<Switch>
<Route exact path="/login" component={Login} />
<Route path="/dashboard" component={Dashboard} />
</Switch>
</div>
</Router>
);

const Login = () => <span>Login Page</span>;

const Dashboard = () => {
return (
<div>
<div>Dashboard Page</div>
<NavLink to="/dashboard/profile">Go to profile</NavLink>
<div>
<Route exact path="/dashboard/profile" component={Profile} />
</div>
</div>
);
};

const Profile = () => {
return <span>Profile Page</span>;
};

export default App;

您可以在此处找到工作示例:https://codesandbox.io/s/z3py3672v3

关于reactjs - React-Router 嵌套路由加载空白页面而不是在父组件内部加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52567566/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com