我正在根据路径显示我的组件:
App.js -
import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom';
import axios from 'axios';
import './App.css';
import Header from './components/header';
import Home from './components/home';
import Page from './components/page';
import Work from './components/work';
class App extends Component {
constructor(props){
super(props);
this.state = {
title: "John Doe",
nav: {}
};
}
getMainMenu(){
axios.get('http://admin.sitedata.com/menus/5')
.then((response) => {
this.setState({nav:response.data});
})
.catch((error) => {
console.log(error);
});
}
componentDidMount(){
this.getMainMenu();
this.triggerMenu = this.triggerMenu.bind(this);
}
triggerMenu(e){
var menuOverlay = document.getElementById('menuOverlay');
if(menuOverlay.classList.contains('active')){
menuOverlay.classList.remove('active');
} else {
menuOverlay.classList.add('active');
}
}
render() {
return (
<div className="App">
<Header nav={this.state.nav} triggerMenu={this.triggerMenu} />
<Router>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/work/:slug" component={Work} />
<Route path="/:slug" component={Page} />
</Switch>
</Router>
</div>
);
}
}
export default App;
这应该呈现当前页面:主页,页面或工作详细信息页面;取决于路径。这在页面加载时工作正常,但是当我点击链接(在Header.js
中维护)时,网址将会更改,但视图不会反映新路径:
header.js -
import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom';
class Header extends Component {
render() {
if(this.props.nav.items){
var navData = this.props.nav;
var pageChange = this.props.pageChange;
var navItems = navData.items.map(function(navItem){
return <li key={navItem.id}><Link to={'/'+navItem.object_slug} className={navItem.classes} data-link={navItem.object_slug}>{navItem.title}</Link></li>;
});
}
return (
<div className="header">
<Router>
<section id="siteHeader">
<div className="menu-overlay overlay" id="menuOverlay" onClick={this.props.triggerMenu}>
<ul>
{navItems}
</ul>
</div>
<header>
<div id="header" className="container">
<a href="/" className="logo"><span>David</span> Powell</a>
</div>
<span id="menuButton" className="trigger-menu" onClick={this.props.triggerMenu}><i className="fa fa-bars"></i></span>
</header>
</section>
</Router>
</div>
);
}
}
export default Header;