react-router - 无法在 this.props.location 中获取信息

react-router - Cannot get information in this.props.location

我有一个从 create-react-app 创建的应用程序,我所有组件的道具位置始终未定义..

这里是index.js

    ReactDOM.render((
<BrowserRouter >
<App/>
</BrowserRouter>
), document.getElementById('root'));
registerServiceWorker();

这是app.js

的简短版本
import {BrowserRouter as Router, Route, Switch} from 'react-router-dom';
class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      auth: UserProfile.getAuth(),
    }

  }

  render() {
    if(this.state.auth){
      return (
        <Router>
          <Switch>
            ...
            <Route path="/editUser" render={()=><EditUser className="App" app={this}/>} />
          </Switch>
        </Router>
      );
    }

    else{
      ...
    }
  }
}

现在是editUser.jsx

class EditUser extends React.Component {
  constructor(props) {
    super(props);
...
}

componentDidMount(){
    console.log(this.props.location) //undefined
  }

render() {
return (<div>...</div>)

我总是变得不确定,我不明白为什么... 我根据我的 package.json

使用 "react-router-dom": "^4.3.1"

请帮忙!

您需要将路由属性传递到组件中,因为您正在使用 <Route/> 组件的 render 属性。

此外,在您的 App 组件中,您不需要 BrowserRouter as Router,因为您已经将 <App/> 包装在 index.js 中。我更改了 import 并删除了包装 <Router/> 组件。

import { Route, Switch } from 'react-router-dom';

class App extends React.Component {
    ...
    render() {
        if (this.state.auth) {
            return (
                <Switch>
                    ...
                    <Route path="/editUser" render={props =>
                        <EditUser {...props} className="App" app={this}/>
                    }/>
                </Switch>
            );
        }
    }
}

我认为你需要在你的 EditUser 组件上使用 withRouter HOC 来注入像位置这样的道具。