简体   繁体   中英

React router - undefined history

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 /

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

 import React, { Component} from 'react';
 import { Link } from 'react-router-dom';
 class Login extends Component {
 constructor(props){
 super(props)
 }
 handleClick(event){
  this.props.history.push('/dashboard')
}
 render() {
  return (
         <Button color="primary" className="px-4"  onClick={this.handleClick.bind(this)}>Login</Button>
          )}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM