你好,我的react项目中有一个单独的路由和链接文件,单击链接时它会更改URL,但不会更改视图,我无法弄清原因。
这是我的index.js
import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter} from 'react-router-dom';
import Routes from "./router";
import RenderSite from './App';
ReactDOM.render(<BrowserRouter><RenderSite /></BrowserRouter>, document.getElementById('site-wrapper'));
这是我的链接文件
import React from 'react';
import { Link } from 'react-router-dom';
const HeaderNav = () => {
return(
<div className="header-links">
<Link to="/" className="link">Home</Link>
<Link to="/about" className="link">About</Link>
<Link to="/contact" className="link">Contact Us</Link>
</div>
);
}
export default HeaderNav;
最后这是我的router.js
import React from 'react'
import HomePage from './pages/home'
import AboutPage from './pages/about'
import ContactPage from './pages/contact'
import {
Switch,
Route
} from 'react-router-dom';
const Routes = () => (
<Switch>
<Route exact path="/" component={HomePage} />
<Route exact path="/about" component={AboutPage} />
<Route exact path="/contact" component={ContactPage} />
</Switch>
);
export default Routes;
为清楚起见,这里是我要加载的页面之一的示例:
import React from 'react'
import PageLayout from '../components/layout'
class AboutPage extends React.Component {
render() {
return (
<div>
<PageLayout />
<p>About page</p>
</div>
);
}
}
export default AboutPage
答案 0 :(得分:0)
导入BrowserRouter
并在BrowserRouter
中包装路线
import React from 'react'
import HomePage from './pages/home'
import AboutPage from './pages/about'
import ContactPage from './pages/contact'
import {
Switch,
Route,
BrowserRouter as Router
} from 'react-router-dom';
const Routes = () => (
<Router>
<Switch>
<Route exact path="/" component={HomePage} />
<Route exact path="/about" component={AboutPage} />
<Route exact path="/contact" component={ContactPage} />
</Switch>
</Router>
);
export default Routes;
答案 1 :(得分:0)
我看不到您的App.js
代码。您已在Routes
中导入了index.js
,但尚未使用。您需要在Routes
组件中添加App
组件。如下所示:
function App(){
return(
<div>
{Routes()}
</div>
)
}