React router, pass data when navigating programmatically?

前端 未结 6 1264
广开言路
广开言路 2020-12-07 12:06

We could navigate to different path using

this.props.router.push(\'/some/path\')

Is there a way to send params (object) along when navigating?

6条回答
  •  不知归路
    2020-12-07 12:42

    The current answers are outdated.

    React Router 6:

    Use the useNavigate hook:

    const navigate = useNavigate();
    navigate('/other-page', { state: { id: 7, color: 'green' } });
    

    Then, you can access the state data in '/other-page' via the useLocation hook:

    const {state} = useLocation();
    const { id, color } = state; // Read values passed on state
    

    React Router 4 or 5:

    Call history.push, and pass an object as the 2nd param to pass state:

    props.history.push('/other-page', { id: 7, color: 'green' }))
    

    Then, you can access the state data in '/other-page' via:

    props.location.state

提交回复
热议问题