javascript - 使用 hashHistory 导航到路由

标签 javascript reactjs ecmascript-6 react-router

我在我的 React 应用程序中设置了我的路线,如下所示:

// App.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, IndexRoute, hashHistory } from 'react-router';

// Pages
import Layout from './pages/Layout/Layout';
import Home from './pages/Home/Home';
import CityOverview from './pages/CityOverview/CityOverview';
import GameOne from './pages/GameOne/GameOne';
import PageTwo from './pages/PageTwo/PageTwo';
import PageThree from './pages/PageThree/PageThree';

ReactDOM.render(
    <Router history={hashHistory}>
        <Route path='/' component={Layout}>
            <IndexRoute component={Home}></IndexRoute>
            <Route path='/city-overview' component={CityOverview}></Route>
            <Route path='/game-one' component={GameOne}></Route>
            <Route path='/page-two' component={PageTwo}></Route>
            <Route path='/page-three' component={PageThree}></Route>
        </Route>
    </Router>,
    document.getElementById('app')
);

但是我很难从一个页面导航到另一个页面,例如:

//主页.js hashHistory.push('/城市概览);

浏览器中的 URL 发生了变化,但它实际上并没有导航到该路由...

最佳答案

我在我的 react-router 组件中使用 contextType

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

并根据某些操作更改组件内的路由 -

this.context.router.replace({
    pathname : '/'/city-overview',
    state    : {
        // some state data if you need to pass
        // key : val
    }
});

关于javascript - 使用 hashHistory 导航到路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41115124/

相关文章:

javascript - 如何使 React 组件更改全局 CSS

javascript - 使用 HTML Canvas 创建反射图像?

javascript - 如何避免生成的 JavaScript 字符串文字包含用于缩进的空格?

javascript - 如何用 react/redux 柯里化(Currying)调度函数?

javascript - import * as _ from 'lodash' 和 import { indexOf } from 'lodash' 之间是否存在性能差异

javascript - JS合并数组并划分合并值

javascript - 在游戏循环中执行一次函数

reactjs - 如何在 React.js 应用程序中将字符串中的特定文本加粗

reactjs - 动态生成的站点地图-站点地图上只有声明的页面

javascript - es6 Javascript 类在回调中使用 this