React Pass history to a component defined in the Router

大城市里の小女人 提交于 2020-07-31 04:28:45

问题


I have this Router in my App.js:

<Router basename={process.env.REACT_APP_ROUTER_BASE || '/MyApp'}>
                <Switch>
                    <Route path="/" exact component={HomePage} />
                    <Route path="/login" component={Login} />
                    <Route path="/editProject" /*render={(props) => <ProjectEdit {...props} history={props.history} />}*/ component={ProjectEdit} />
                    {/*<Redirect path="*" to="/" />*/}
                </Switch>
            </Router>

From HomePage component I'm using < ProjectsList> component which have < Project> components. Within the < Project> component I have an option of the menu for Editing a project and I'm trying to use there:

 <OverflowMenuItem itemText="Edit" href="#" onClick={ () => this.props.history.push('/editProject')}/>

But I'm getting that props is undefined!

Resolution:

I passed the props.history as a prop history= {this.props.history} in this order:

HomePage -> ProjectsList -> Project


回答1:


If you are working with a Functional Component, you can simply access the history instance object within your component using the useHistory hook, as stated on the React-Router documentation.

import { useHistory } from 'react-router-dom';


function HomeButton() {
  let history = useHistory();

  function handleClick() {
    history.push("/home");
  }

  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  );
}

If you are working with a Class Component, you can wrap your component with withRouter, and then access the history object within your component

import { withRouter } from 'react-router';

class YourComponent extends React.Component {

  render() {
    const { history } = this.props;

    return <OverflowMenuItem itemText="Edit" href="#" onClick={ () => history.push('/editProject')}/>;
  }
}

export default withRouter(YourComponent);


来源:https://stackoverflow.com/questions/59453964/react-pass-history-to-a-component-defined-in-the-router

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