最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React router - undefined history - Stack Overflow

programmeradmin2浏览0评论

I am trying to use the 1.0.0-rc1 react-router and history 2.0.0-rc1 to navigate manually through the website after pressing the button. Unfortunately, after pressing the button I get:

Cannot read property 'pushState' of undefined

My router code:

import React from 'react';
import { Router, Route, Link, browserHistory } from 'react-router'
import AppContainer from './components/AppContainer.jsx';
import MyTab from './components/test/MyTab.jsx';
import MainTab from './components/test/MainTab.jsx';


var routes = (
    <Route component={AppContainer} >
        <Route name="maintab" path="/" component={MainTab} />
        <Route name="mytab" path="/mytab" component={MyTab} />
    </Route>
);

React.render(<Router history={browserHistory}>{routes}</Router>, document.getElementById('main'));

The navigation button is on MyTab and it attemps to navigate to MainTab:

import React from 'react';
import 'datejs';
import History from "history";
export default React.createClass({

    mixins: [ History ],

    onChange(state) {
        this.setState(state);
    },

    handleClick() {
        this.history.pushState(null, `/`)
    },

    render() {
        return (
            <div className='container-fluid' >
                <button type="button" onClick={this.handleClick.bind(this)}>TEST</button>
            </div>

        );
    }
});

When I use history with this.props.history everything works fine. What is the problem with this code?

EDIT.

After adding the following:

const history = createBrowserHistory();

React.render(<Router history={history}>{routes}</Router>, document.getElementById('main'));

I try to access my app. Before (without history={history}), I just accessed localhost:8080/testapp and everything worked fine - my static resources are generated into dist/testapp directory. Now under this URL I get:

Location "/testapp/" did not match any resources

I tried to use the useBasename function in a following way:

    import { useBasename } from 'history'
    const history = useBasename(createBrowserHistory)({
    basename: '/testapp'
});

React.render(<Router history={history}>{routes}</Router>, document.getElementById('main'));

and the application is back, but again I get the error

Cannot read property 'pushState' of undefined

in the call:

handleClick() {
    this.history.pushState(null, `/mytab`)
},

I thougt it may be because of my connect task in gulp, so I have added history-api-fallback to configuration:

settings: {
      root: './dist/',
      host: 'localhost',
      port: 8080,
      livereload: {
        port: 35929
      },
      middleware: function(connect, opt){
        return [historyApiFallback({})];
      }
    }

But after adding middleware all I get after accessing a website is:

Cannot GET /

I am trying to use the 1.0.0-rc1 react-router and history 2.0.0-rc1 to navigate manually through the website after pressing the button. Unfortunately, after pressing the button I get:

Cannot read property 'pushState' of undefined

My router code:

import React from 'react';
import { Router, Route, Link, browserHistory } from 'react-router'
import AppContainer from './components/AppContainer.jsx';
import MyTab from './components/test/MyTab.jsx';
import MainTab from './components/test/MainTab.jsx';


var routes = (
    <Route component={AppContainer} >
        <Route name="maintab" path="/" component={MainTab} />
        <Route name="mytab" path="/mytab" component={MyTab} />
    </Route>
);

React.render(<Router history={browserHistory}>{routes}</Router>, document.getElementById('main'));

The navigation button is on MyTab and it attemps to navigate to MainTab:

import React from 'react';
import 'datejs';
import History from "history";
export default React.createClass({

    mixins: [ History ],

    onChange(state) {
        this.setState(state);
    },

    handleClick() {
        this.history.pushState(null, `/`)
    },

    render() {
        return (
            <div className='container-fluid' >
                <button type="button" onClick={this.handleClick.bind(this)}>TEST</button>
            </div>

        );
    }
});

When I use history with this.props.history everything works fine. What is the problem with this code?

EDIT.

After adding the following:

const history = createBrowserHistory();

React.render(<Router history={history}>{routes}</Router>, document.getElementById('main'));

I try to access my app. Before (without history={history}), I just accessed localhost:8080/testapp and everything worked fine - my static resources are generated into dist/testapp directory. Now under this URL I get:

Location "/testapp/" did not match any resources

I tried to use the useBasename function in a following way:

    import { useBasename } from 'history'
    const history = useBasename(createBrowserHistory)({
    basename: '/testapp'
});

React.render(<Router history={history}>{routes}</Router>, document.getElementById('main'));

and the application is back, but again I get the error

Cannot read property 'pushState' of undefined

in the call:

handleClick() {
    this.history.pushState(null, `/mytab`)
},

I thougt it may be because of my connect task in gulp, so I have added history-api-fallback to configuration:

settings: {
      root: './dist/',
      host: 'localhost',
      port: 8080,
      livereload: {
        port: 35929
      },
      middleware: function(connect, opt){
        return [historyApiFallback({})];
      }
    }

But after adding middleware all I get after accessing a website is:

Cannot GET /

Share Improve this question edited Jan 5, 2016 at 8:29 TheMP asked Jan 4, 2016 at 16:49 TheMPTheMP 8,4279 gold badges45 silver badges74 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 5

As of "react-router": "^4.1.1", you may try the following:

Use 'this.props.history.push('/new-route')'. Here's a detailed example

1: Index.js

 import { BrowserRouter, Route, Switch } from 'react-router-dom'; 
 //more imports here
    ReactDOM.render(
      <div>
        <BrowserRouter>
           <Switch>
              <Route path='/login' component={LoginScreen} />
              <Route path='/' component={WelcomeScreen} />
           </Switch>
        </BrowserRouter>
     </div>, document.querySelector('.container'));

Above, we have used BrowserRouter, Route and Switch from 'react-router-dom'.

So whenever you add a component in the React Router 'Route', that is,

<Route path='/login' component={LoginScreen} />

..then 'React Router' will add a new property named 'history' to this component (LoginScreen, in this case). You can use this history prop to programatically navigate to other rountes.

So now in the LoginScreen component you can navigate like this:

2: LoginScreen:

return (
      <div>
       <h1> Login </h1>
       <form onSubmit={this.formSubmit.bind(this)} >
         //your form here
       </form>
      </div>

    );



formSubmit(values) {
 // some form handling action
   this.props.history.push('/'); //navigating to Welcome Screen
}

Because everything changes like hell in react world here's a version which worked for me at December 2016:

import React from 'react'
import { Router, ReactRouter, Route, IndexRoute, browserHistory } from 'react-router';

var Main = require('../components/Main');
var Home = require('../components/Home');
var Dialogs = require('../components/Dialogs');

var routes = (
    <Router history={browserHistory}>
        <Route path='/' component={Main}>
            <IndexRoute component={Home} />
            <Route path='/dialogs' component={Dialogs} />
        </Route>
    </Router>
);

module.exports = routes

To create browser history you now need to create it from the History package much like you've tried.

import createBrowserHistory from 'history/lib/createBrowserHistory';

and then pass it to the Router like so

<Router history={createBrowserHistory()}>
    <Route />
</Router>

The docs explain this perfectly

发布评论

评论列表(0)

  1. 暂无评论