ReactJS 如何在 app.js 文件中使用路由器的道具

ReactJS How to use Router's props inside app.js file

我项目的app.js文件如下。对于所有其他组件,我使用 this.props.history.push('/') 重定向到特定路径,并且它在这些组件收到 props 时工作。但是在这个 app.js 中,我试图控制 constructorcomponentWillMountrender 中的道具值,但都给出了空数组。有什么办法可以在 app.js 中使用 this.props.history.push('/') 吗?

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {};
    console.log(this.props)
  }

  componentWillMount(){ 
    console.log(this.props)
    this.props.history.push('/')
  }

  render() {
    console.log(this.props)
    return (
        <Router>
            <div className="App">
                <Route exact path='/' render={(props) => <Login {...props} />} />
                <Route exact path='/dashboard' render={(props) => <Dashboard {...props}/>}/>
            </div>
        </Router>
    );
  }
}

export default App;

使用withRouter

import { withRouter } from 'react-router-dom'

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {};
    console.log(this.props)
  }

  componentWillMount(){ 
    console.log(this.props)
    this.props.history.push('/')
  }

  render() {
    console.log(this.props)
    return (
        <Router>
            <div className="App">
                <Route exact path='/' render={(props) => <Login {...props} />} />
                <Route exact path='/dashboard' render={(props) => <Dashboard {...props}/>}/>
            </div>
        </Router>
    );
  }
}

export default withRouter(App);

这将使您能够访问历史对象并允许您推送到新路由。 (我在发布前进行了测试和验证,所以我知道这是有效的)。

将它导入文件的顶部,然后将 App 与它一起包装在 export default