在使用React Router v4渲染组件时,出现了问题。在应用程序首次加载时,它将呈现与URL对应的正确组件。但是,随后的任何Link
点击都无法呈现所需组件。
使用的库
- React Router: 4.2.2
- React: 15.6.1
- React DOM: 15.6.1
- -- 只是提及受影响的库 --
- React Redux: 5.0.6
- Redux: 3.7.2
- Material UI: 0.19.0
出于简洁的考虑,省略了一些imports
网站结构
index.jsx
|
App.jsx
|
Auth.jsx
|
Layout.jsx
<Routes />
index.jsx
import React from 'react';
import store from './store.js';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { BrowserRouter } from 'react-router-dom';
import createBrowserHistory from 'history/createBrowserHistory';
const history = createBrowserHistory();
import App from './containers/App.jsx';
ReactDOM.render(
<Provider store={store}>
<MuiThemeProvider muiTheme={muiTheme}>
<BrowserRouter>
<App />
</BrowserRouter>
</MuiThemeProvider>
</Provider>,
document.getElementById('root')
);
App.jsx
import React, { Component } from 'react';
import Auth from '../components/Auth.jsx';
class App extends Component {
render() {
return <Auth />;
}
}
Auth.jsx
import React from 'react';
import { Route } from 'react-router-dom';
import Layout from './Layout.jsx';
export default function Auth(props) {
//this Has a render function to render a Loader, Error Page, or the Layout
return <Layout />;
}
Layout.jsx
渲染整个应用程序需要更多复杂的操作。在将其他布局组件注释掉并使项目更加模块化之前,我将仅使用一些链接和 Switch
组件来使其正常工作。
import React, { Component } from 'react';
import { Link, Switch, Route } from 'react-router-dom';
import Overview from './views/overview/Overview.jsx';
import Home from './views/home/Home.jsx';
export default class Layout extends Component {
render() {
return (
<div className="layout">
{/* <TopBar /> */}
{/* <AppBar/> */}
{/* <Drawer>
<MainMenu/>
</Drawer> */}
<Link to="/">HOME</Link>
<Link to="/overview">Overview</Link>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/overview" component={Overview} />
</Switch>
{/* <Routes /> */}
{/* <Footer /> */}
</div>
);
}
}
Routes.jsx
这是我想要路由组件看起来的样子。
import React from 'react';
import { Switch, Route } from 'react-router-dom';
import Home from './views/home/Home.jsx';
import Overview from './views/overview/Overview.jsx';
import Admin from './views/admin/Admin.jsx';
import NotFound from './NotFound.jsx';
export default function Routes(props) {
return (
<Switch>
<Route path="/" exact component={Home} />
<Route path="/overview" component={Overview} />
<Route path="/admin" component={Admin} />
<Route component={NotFound} />
</Switch>
);
}
我点击 Link
后没有看到组件渲染,是否有遗漏?控制台没有错误信息,也没有提示问题所在。不确定是否组件没有正确包装或其他问题导致出现问题。
withRouter
?我正在使用配置设置路由:[https://reacttraining.com/react-router/web/example/route-config] - thirdtiu