react路由router
程序员文章站
2022-03-26 13:40:23
...
安装
- 如果你没有安装脚手架工具,你需要安装一下:
npm install -g create-react-app
- 直接使用脚手架工具创建项目
在项目跟目录下安装
npm install --save react-router-dom
index.js中引入
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import {BrowserRouter as Router} from 'react-router-dom'
ReactDOM.render(
<Router>
<App />
</Router>
,
document.getElementById('root'));
App中引入
import React, { Component } from 'react'
import { Switch, Route, Link,Redirect } from 'react-router-dom'
import MyPage from './pages/MyPage'
import NewsPage from './pages/NewsPage'
import NovelPage from './pages/NovelPage'
import styleObj from './app.module.scss'
class App extends Component {
constructor(props) {
super(props)
}
render() {
return (
<div className={styleObj['app-page']}>
<div className={styleObj['footer-nav']}>
<div className={styleObj['nav']}>
<Link to="/my">我的</Link>
</div>
<div className={styleObj['nav']}>
<Link to="/news">新闻</Link>
</div>
<div className={styleObj['nav']}>
<Link to="/novel">小说</Link>
</div>
</div>
<div className={styleObj['content']}>
<Switch>
{/* <Route path="/" exact component={NewsPage} /> */}
<Route path="/my" component={MyPage} />
<Route path="/news" component={NewsPage} />
<Route path="/novel" component={NovelPage} />
<Redirect to="/novel"></Redirect>
</Switch>
</div>
</div>
)
}
}
export default App
动态路由
import React from 'react'
import {Switch, Route, Link} from 'react-router-dom'
import NewsDetail from './NewsDetail'
class Recomment extends React.Component {
constructor (props){
super(props);
}
goToDetail = () => {
debugger
// 直接跳转到 制定的 URL
// this.props.history.push('/news/recomment/6666');
// 通过API 实现路由切换
this.props.history.push({
// 指明跳转的路由地址
pathname: '/news/recomment/7777',
// 地址栏后面添加 “?” 后面的参数
search: '?name=qiqi&age=18',
// 在?后面添加 # 的数据
hash: '#/aaaa/bbbbb'
})
}
render () {
return (
<div>
<div>
<ul>
<li>
<Link to='/news/recomment/88888'>新闻1</Link>
</li>
<li>
<Link to='/news/recomment/3333'>新闻2</Link>
</li>
<li onClick={this.goToDetail}>新闻3</li>
<li>新闻4</li>
</ul>
</div>
<div>
新闻的内容
<Switch>
{/*
使用 ":/变量名" 来定义动态路由
this.props.match.params.变量名 来获取路由的参数
*/}
<Route path='/news/recomment/:newsId' component={NewsDetail}></Route>
</Switch>
</div>
</div>
)
}
}
export default Recomment;
0917
推荐阅读
-
通过vue-router懒加载解决首次加载时资源过多导致的速度缓慢问题
-
react 列表滚动触发回调
-
react-three-fiber 加载 obj / gltf 格式的文件
-
React hooks-useEffect | 解决报错Warning...cancel all subscriptions and asynchronous tasks in a useEffect
-
React hook 报错Warning...cancel all subscriptions and asynchronous tasks in a useEffect cleanup fn
-
React 之 cancel all subscriptions and asynchronous tasks in the componentWillUnmount method
-
Yaf中map路由下delimiter的问题,yafdelimiter
-
PHP路由性能测试
-
React学习笔记(一)
-
怎样使用React为Vue引入容器组件+展示组件