React Router: Cannot read property 'pathname' of undefined

有些话、适合烂在心里 提交于 2019-12-22 01:26:05

问题


I've just started learning React and got stuck at this error.

Uncaught TypeError: Cannot read property 'pathname' of undefined at new Router

Here is my code:

var React = require('react');
var ReactDOM = require('react-dom');
var { Route, Router, IndexRoute } = require('react-router');
var hashHistory = require('react-router-redux')

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

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

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

The tutorial I was following uses React-Router 2.0.0, but on my desktop I'm using 4.1.1. I tried searching for changes but was unsuccessful in finding a solution that worked.

"dependencies": {
"express": "^4.15.2",
"react": "^15.5.4",
"react-dom": "^15.5.4",
"react-router": "^4.1.1",
"react-router-dom": "^4.1.1",
"react-router-redux": "^4.0.8"

回答1:


The error is because the api in React Router v4 is totally different. You can try this:

import React from 'react';
import ReactDOM from 'react-dom';
import {
  BrowserRouter as Router,
  Route
} from 'react-router-dom';

const Main = () => <h1>Hello world</h1>;

ReactDOM.render(
  <Router>
    <Route path='/' component={Main} />
  </Router>,
  document.getElementById('app')
);

You can review the documentation to learn how it works now.

Here I have a repo with routing animation.

And here you can find a live demo.




回答2:


I got the above error message and it was extremely cryptic. I tried the other solutions mentioned and it didn't work.

Turns out I accidentally forgot to include the to prop in one of the <Link /> components.

Wish the error message was better. A simple required prop "to" not found or something like that would have been helpful. Hopefully this saves someone else who has encountered the same problem some time.




回答3:


I had the same error and I resolved it by updating history from 2.x.x to 4.x.x

npm install history@latest --save




回答4:


I had a different cause, but the same error and came across this question because of it. Putting this here in case the same happens for others and it may help. The issue for me was that I had updated to react-router-4 and accessing pathname has changed.

Change: (React-Router-3 & earlier)

this.props.location.pathname

To: (React-Router-4)

this.props.history.location.pathname




回答5:


Just be sure that you add a to props to <Link> otherwise you would also get the same error.



来源:https://stackoverflow.com/questions/43620289/react-router-cannot-read-property-pathname-of-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!