今天裝完react-router,寫完測試代碼要啟動server測試,竟然出現xxx undefined!!上網一查才發現,現行的v4和之前的v3寫法不一樣,而且Router已變成BrowserRouter,這個坑實在是很機車只好再去官網慢慢爬文件。我還沒有把文件給爬完,先分享一些基礎應用。
react-router-web
https://reacttraining.com/react-router/web/guides/philosophy
安裝reactrouter
npm install react-router-dom
Link to對應Route path互相映射,每當點擊Link對應Route path切換到不同的component。
src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import SayHi from './SayHi';
import App from './App';
import {
BrowserRouter as Router,
Route,
Link
} from 'react-router-dom'
import registerServiceWorker from './registerServiceWorker';
const Repos = () => (
<div>
<h2>Repos</h2>
</div>
)
const About = () => (
<div>
<h2>About</h2>
</div>
)
ReactDOM.render(
<Router>
<div>
<ul>
<li><Link to="/">App</Link></li>
<li><Link to="/repos">Repos</Link></li>
<li><Link to="/about">About</Link></li>
<li>
<Link to={{
pathname: '/sayhi',
state: { id: '1', message: 'hello, component' }
}}>SayHi</Link>
</li>
</ul>
<hr/>
<Route exact path="/" component={App}/>
<Route path="/repos" component={Repos}/>
<Route path="/about" component={About}/>
<Route path="/sayhi" render={props =><SayHi name="joe" {...props} />} />
</div>
</Router>,
document.getElementById('root'));
registerServiceWorker();
src/SayHi.js
import React, { Component } from 'react';
class SayHi extends React.Component {
constructor(props) {
super(props);
console.log('url:'+props.match.url);
console.log(this.props.location.state.message);
this.state = {date: new Date()};
}
render() {
return <h1>{this.state.date.toLocaleTimeString()} Hi, {this.props.name}</h1>;
}
}
export default SayHi;
顯示畫面App
顯示畫面SayHi,console.log秀出傳遞訊息