Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
764 views
in Technique[技术] by (71.8m points)

reactjs - React-router TypeError: _this.props.history is undefined

I am using react-router with react js and i following their documentation but facing this error

while compiling it shows the error,

TypeError: _this.props.history is undefined

this is my index.js file

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
import { Router, Route, browserHistory, IndexRoute } from 'react-router';

ReactDOM.render(
  <Router history={browserHistory}>
    <Route path="/" component={App}>

    </Route>
  </Router>
  ,
  document.getElementById('root')
);

and this is my App.js file

import React, { Component } from 'react';
import './App.css';

class App extends Component {
    constructor(props){
        super(props);

        this.state = {
            headerText: "Props from Header.",
            contentText: "Props from content."
        };
    }
    render() {
        return (
          <div className="App">
            <ul>
                <li><a href="">Home</a></li>
                <li><a href="">Home</a></li>
                <li><a href="">Home</a></li>
            </ul>
          </div>
        );
    }
}

export default App;
question from:https://stackoverflow.com/questions/42857283/react-router-typeerror-this-props-history-is-undefined

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is because things changed in React Router starting with 4.0.0. You should now use BrowserRouter from react-router-dom package when you were using browserHistory. So your code will looks like:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
import { BrowserRouter, Route } from 'react-router-dom';

ReactDOM.render(
    <BrowserRouter>
        <Route path="/" component={ App }/>
    </BrowserRouter>, document.getElementById('root')
);

Of course, you'll need to install react-router-dom first.

Also note that if you're using more than one Route element, you'll have to use a Switch as explained in this answer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...