react 路径跳转组件不跳转_【已解决】ReactJS中react-router v4的this.context.router.history.push无法跳转页面...

博客主要讲述了 React 路径跳转组件无法跳转页面的问题。代码虽无语法错误但无法跳转,原因是使用的 react-router 旧版本例子不适用于新版本 v4。经搜索和修改,发现是地址中多了前缀及首页未加 exact 属性,最终优化跳转代码解决问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

折腾:

之后,虽然没有语法错误了。但是却无法跳转页面。

对应代码:

app.jsimport React, { Component } from ‘react’;

// import { Router, Route, IndexRoute } from ‘react-router’;

// import { BrowserRouter } from ‘react-router-dom’;

import {

BrowserRouter as Router,

Route,

Link,

Switch

} from ‘react-router-dom’;

import Main from ‘./main/main’;

import Login from ‘./login/login’;

export default class App extends Component {

。。。

return (

);

}

}

login.jsconsole.log(this);

console.log(this.context);

console.log(this.context.router);

if (this.context.router) {

this.context.router.history.push(‘/main’);

}

无法跳转页面

感觉是:

网上虽然很多react-router的例子,但是都是旧的版本的。

新版本v4的,写法很多不一样。

所以去搜:

reactjs react-router v4 example

去改为:

和:this.context.router.history.push(‘/rse_web/main’);

还真的就可以实现了页面跳转了:

很明显,之前页面没有跳转的原因是:

地址中多了/rse_web这个前缀。

以及好像首页/没有加上exact属性。

记得之前哪里说的,是可以统一加上这个前缀的。

官网不建议用context,因为这个不是官网明确支持的,但是很多人这么用而已。

如果不是不得已,尽量不要用context。

所有的例子都在官网的例子中:

去找找此处的BrowserRouter的是否有对应参数

react-router v4 BrowserRouter

->

->

“basename: string

The base URL for all locations. If your app is served from a sub-directory on your server, you’ll want to set this to the sub-directory. A properly formatted basename should have a leading slash, but no trailing slash.”

我此处找的就是:basename

【总结】

此处之所以:

this.context.router.history.push

无法跳转页面,主要是地址跳转错误。

经过优化改为:

然后跳转页面改为:this.context.router.history.push(‘/main’);

即可调转到:

页面了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值