项目结构如下
路由文件如下
import React from 'react';
import {BrowserRouter as Router,Route} from 'react-router-dom';
import MainPage from './mainPage'
import City from './city'
export default class Main extends React.Component{
render(){
return(
<Router>
<Route exact path='/' component={MainPage}></Route>
<Route exact path='/city' component={City}></Route>
</Router>
)
}
}
MainPage组件如下
import React from 'react';
import { Link } from 'react-router-dom';
export default class MainPage extends React.Component {
constructor(props) {
super(props);
}
render() {
// eslint-disable-next-line no-lone-blocks
{
console.log(window.localStorage.getItem('city'))
if (window.localStorage.getItem('city')!==null) {
return (
<div>
你选择的城市是{localStorage.getItem('city')}
</div>)
} else {
return (
<div>
<Link to='/city'>选择城市</Link>
</div>
)
}
}
}
}
city组件如下
import React from 'react';
export default class City extends React.Component{
constructor(props){
super(props);
this.state = {
city:'--选择省市--'
}
}
handleChange(e){
console.log("1"+e.target.value)
// this.setState是一个异步,所以如果要输出就必须放在回调函数中
this.setState({city:e.target.value},()=>{
console.log("0"+this.state.city)
})
window.localStorage.setItem('city',e.target.value);
window.location.href = '/'
}
render(){
return(
<select value={this.state.city} onChange={this.handleChange.bind(this)}>
<option value='--选择省市--'>--选择省市--</option>
<option value="北京">北京</option>
<option value="天津">天津</option>
<option value="上海">上海</option>
</select>
)
}
}
效果如下