React 路由5版本的使用详解(基于Class类版本的使用react-router-dom@5)

React-Router-Dom 注意事项

1.整个SPA页面只能有一个路由器 BrowserRouter或者HashRouter
root.render(
     <React.StrictMode>
         {/* 只能有且只有一个路由器 */}
        <BrowserRouter>
         {/* SPA 单页面 */}
        <App></App>
        </BrowserRouter>
     </React.StrictMode>
)
2.路由Route 一般都被包裹在Switch组件里

1.route 有两个属性,一个是path 代表路径,一个是component代表组件

       <Switch>
          <Route path="/Login" component={Login}></Route>
          <Route path="/Home" component={Home}></Route>
          <Redirect to="/Login"></Redirect>
        </Switch>
3. UI中的路由跳转,一般用NavLink或者Link,有选中效果一般是NavLink(声明式导航)

1.NavLink和Link 都有 to 代表跳转的属性
2.NavLink 中的activeClassName 设置选中状态的类名

<li>
   <NavLink to="/Home/About" activeClassName="active">
     关于我们
   </NavLink>
  </li>
<li>
  <NavLink to="/Home/News" activeClassName="active">
    新闻列表
  </NavLink>
</li>
4.Redirect 组件为路由重定向组件

1.属性from 从那个页面来,属性to重定向哪个页面去

5.React-Router-Dom 请求参数的三种模式

1.params 模式

1.路由链接携带参数
<Link to={`/Home/News/Detail/${item.id}/${item.title}/${item.content}`}>
  {item.id}={item.title}={item.content}
</Link>
2.注册路由(声明接收)
<Route component={Detail} path="/Home/News/Detail/:id/:title/:content"></Route>
3.接收参数
this.props.match.params

2.search参数模式

1.路由链接携带参数
 <Link to={`/Home/News/Detail?${item.id}&${item.title}&${item.content}`}>
     {item.id}={item.title}={item.content}
 </Link>
 2.注册路由(声明接收)
 <Route component={Detail} path="/Home/News/Detail"></Route>
 3.接收参数
 this.props.location.search
 参数模式?key1=value1&key2=value2&key3=value3模式
 安装querystring 
 import qs from "querystring"
 const getResult= qs.parse(this.props.location.search.slice(1))//解析成一个对象
 

3.state参数

1.路由链接携带参数
  <Link to={{pathname: "/Home/News/Detail",state: {id: item.id,title: item.title,content: item.content,},}}>
    {item.id}={item.title}={item.content}
  </Link>
2.注册路由(声明接收)
 <Route component={Detail} path="/Home/News/Detail"></Route>
3.接收参数
this.props.location.state
//备注:刷新也可以保留住参数

######6. React-Router-Dom 编程式导航
1.push 跳转+携带params参数

 props.history.push(`/Home/News/Detail/${id}/${title}`);

2.push跳转+携带search参数

props.history.push(`/Home/News/Detail?id=${id}&title=${title}`);

3.push跳转+携带state参数

props.history.push(`/Home/News/Detail`, { id, title });

4.前进

this.props.history.goForward();

5.回退

this.props.history.goForward();

6.前进或者回退

this.props.history.go(-2); //回退到前2条的路由
在一般组件中使用编程式路由导航(非路由组件)
import {withRouter} from 'react-router-dom
class Header extends Component {
    // withRouter(Header)后,就可以在一般组件内部使用 this.props.history 
    //...
}
export default withRouter(Header)
  • 10
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值