我尝试使用最简单的代码来理解React路由器。 我带了网站的例子:" https://reacttraining.com/react-router/web/example/basic"并且只改变了一件事,组件'关于'。
import React from 'react'
import ReactDOM from 'react-dom'
import registerServiceWorker from './registerServiceWorker'
import {
BrowserRouter as Router,
Route,
Link
} from 'react-router-dom'
const BasicExample = () => (
<Router>
<div>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/topics">Topics</Link></li>
</ul>
<hr/>
<Route exact path="/" component={Home}/>
<Route path="/about/:aaa" component={About}/>
<Route path="/topics" component={Topics}/>
</div>
</Router>
)
const Home = () => (
<div>
<h2>Home</h2>
</div>
)
class About extends React.Component {
render() {
return (
<div>
<h2>About</h2>
</div>
);
}
}
const Topics = ({ match }) => (
<div>
<h2>Topics</h2>
<ul>
<li>
<Link to={`${match.url}/rendering`}>
Rendering with React
</Link>
</li>
<li>
<Link to={`${match.url}/components`}>
Components
</Link>
</li>
<li>
<Link to={`${match.url}/props-v-state`}>
Props v. State
</Link>
</li>
</ul>
<Route path={`${match.url}/:topicId`} component={Topic}/>
<Route exact path={match.url} render={() => (
<h3>Please select a topic.</h3>
)}/>
</div>
)
console.log('Topics', Topics);
const Topic = ({ match }) => (
<div>
<h3>{match.params.topicId}</h3>
</div>
)
export default BasicExample
ReactDOM.render(<BasicExample />, document.getElementById('root'));
registerServiceWorker();
如果我使用:
class About extends React.Component {
render() {
return (
<div>
<h2>About</h2>
</div>
);
}
}
React-router不显示此组件。为什么我要用这个?因为有了这个我可以使用State。
也许我会在那里找到答案。然后我会来编辑......