fullstack react 学习笔记 Routing
示例代码;
解释:
(1)BrowserRouter
BrowserRouter相对于NativeRouter而言,它的主要作用是提供上下文,history和window.location;
(2)Link和Redirect
Link和Redirect非常的相似,都是切换到另外一个组件,后面都跟有to代表重定向的地址,不同的是Link包含组件的,而Redirect是自闭和的标签,仅仅是指向已经存在的Link.
(3)Route
Route是代表要显示的组件及其路径,path代表路径,component代表已经定义的组件,render可以实现在行内定义新组件。
(4)Switch
Switch的作用是当Switch将所有的Route包含在内部的情况下,Route寻址的话不会match所有的组件,而是只会返回找到的第一个组件,因此我们可以把二级路径放在一级路径的前面,这样就等于给所有Route 增加了exact={true}的属性。其次可以在最后一个Route上增加一个对所有不存在的路径对应的提示,以便于用户输入不存在路径时给予回应。
import React from 'react';
import {
BrowserRouter as Router,
Route,
Link,
Redirect,
Switch,
} from 'react-router-dom'
const App = () => (
<Router>
<div
className='ui text container'
>
<h2 className='ui dividing header'>
Which body of water?
</h2>
<ul>
<li>
<Link to='/atlantic'>
<code>/atlantic</code>
</Link>
</li>
<li>
<Link to='/pacific'>
<code>/pacific</code>
</Link>
</li>
<li>
<Link to='/black-sea'>
<code>/black-sea</code>
</Link>
</li>
</ul>
<hr />
<Switch>
<Route path='/atlantic/ocean' render={() => (
<div>
<h3>Atlantic Ocean — Again!</h3>
<p>
Also known as "The Pond."
</p>
</div>
)} />
<Route path='/atlantic' component={Atlantic} />
<Route path='/pacific' component={Pacific} />
<Route path='/black-sea' component={BlackSea} />
<Route exact path='/' render={() => (
<h3>
Welcome! Select a body of saline water above.
</h3>
)} />
<Route render={({ location }) => (
<div className='ui inverted red segment'>
<h3>
Error! No matches for <code>{location.pathname}</code>
</h3>
</div>
)} />
</Switch>
</div>
</Router>
);
const Atlantic = () => (
<div>
<h3>Atlantic Ocean</h3>
<p>
The Atlantic Ocean covers approximately 1/5th of the
surface of the earth.
</p>
</div>
);
const Pacific = () => (
<div>
<h3>Pacific Ocean</h3>
<p>
Ferdinand Magellan, a Portuguese explorer, named the ocean
'mar pacifico' in 1521, which means peaceful sea.
</p>
</div>
);
class BlackSea extends React.Component {
state = {
counter: 3,
};
componentDidMount() {
this.interval = setInterval(() => (
this.setState(prevState => {
return {
counter: prevState.counter - 1,
};
}
)), 1000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
render() {
return (
<div>
<h3>Black Sea</h3>
<p>Nothing to sea [sic] here ...</p>
<p>Redirecting in {this.state.counter}...</p>
{
(this.state.counter < 1) ? (
<Redirect to='/' />
) : null
}
</div>
);
}
}
export default App;
浙公网安备 33010602011771号