react-router4.0组件外怎么跳转
发布于 7 年前 作者 pengchengzhong 8167 次浏览 来自 问答

react-router4.0组件外路由怎么跳转,3.0的会,4.0的没有browersHistory了,不能用了

18 回复

withRouter, 4.0也可以用browserHistory

@Cacivy 我再看看,没看懂这个 <br><br>来自<a href=“https://lzxb.github.io/react-cnode/” target="_blank">react-cnode手机版</a>

应该都是push吧

遇到同样的问题,不知道该如何解决!

什么是组件外跳转? 是想在代码里根据判断条件,然后跳转不同的页面吗?

4.0 文档有browersHistory 名字叫 BrowserRouter

只要是路由组件都在组件内部都有this.props.history.push 要不是路由组件 withRouter(组件)

  static contextTypes = {
    router: PropTypes.object.isRequired
  }

this.context.router

@1340641314 谢谢,应该是这样的 <br><br>来自<a href=“https://lzxb.github.io/react-cnode/” target="_blank">react-cnode手机版</a>

hash和brower有什么区别,一直不太清楚。。

@FateZeros Main.contextTypes = { router: PropTypes.object.isRequired }

this.context.router.history.push({ pathname: ‘/user/’ + res.loginname }); <br><br>来自<a href=“https://lzxb.github.io/react-cnode/” target="_blank">react-cnode手机版</a>

@pengchengzhong 官网是这样来组件外部跳转组件的 <br><br>来自<a href=“https://lzxb.github.io/react-cnode/” target="_blank">react-cnode手机版</a>

@FateZeros 其实就是你的生成的UR是否带#号而已

@pengchengzhong 用withRouter把组件包住就可以用 this.props.history.push('/login'); 这种方式跳转了

另外react-router(v2, v3)里也是要用withRouter把组件包一下,然后再声明一下

YourComponent.contextTypes = {
  router: PropTypes.object.isRequired
};

然后就可以用 this.context.router.push('/login')

另外路由的返回 V4: this.props.history.goBack

v2, v3: this.context.router.goBack();

最后吐嘈一下你的app 回复尾巴,你把它改成markdown不就不会显示html代码了,现在这样看着真不舒服

@liygheart 额,我这是在自己写的一个cnode的react项目里面直接回复的,还没写用markdown组件呢

@liygheart 感谢,已经找到了,谢谢

我用的redux-saga,解决如下:

//utils.js
import createHistory from 'history/createBrowserHistory';

export const history = createHistory()

router

import { history } from '../utils/history'

export default class App extends Component{
    render(){
        return (
            <Router history={history}>
                <Switch>  
                    <Route exact path="/" component={Home}></Route>
                    <Route path="/Dashboard" component={Dashboard} />
                    <Route path="/signin" component={Login} />
                    <Route path="/signup" component={Register}></Route>
                    <Route path="/forget" component={Forget}></Route>
                </Switch>  
            </Router>
        )
  

saga

import { history } from '../utils/history';
import { camelCase } from '../utils';
let watchGenerator = [];
let watchList = Object.keys(API);

function* fetchEntity(entity, url, data, cb) {

  // let hide = ''
  // if(!~url.indexOf('total'))hide = message.loading('加载中...', 0);
  yield put( entity.request(data) )
  const {response, error} = yield call(api.fetchData, {url: url, data});
  if(response){
    // setTimeout(hide, 0);
    if(response.data.code == 105){
        history.replace('/');
        return;
    }

@pengchengzhong 我的意思是你把这个

来自<a href=“https://lzxb.github.io/react-cnode/” target="_blank">react-cnode手机版</a> 改成

来自[react-cnode手机版](https://lzxb.github.io/react-cnode/) 就可以了

回到顶部