简体   繁体   中英

How to properly use useHistory () from react-router-dom?

How to use useHistory() correctly? I can't make the transition from one react component to another. According to the instructions from the React documentation and also here on Stack Overflow, I cannot make the transition from App.js to MyComponent.js.

For example - I am trying

/* **App.js ** */
/* Import modules */
import React from 'react';
import { useHistory } from 'react-router-dom'; // version 5.2.0

function App()
{
    let history = useHistory ();
    const handleClick = () => {
       history.push ('./pages/MyComponent');
    }    

    return (
       <div className="App">
          <button onClick={handleClick}>Next page ==></button>
       </div>
    );
}

I also tested this example, but the output throws the following error when the button is pressed:

TypeError: Cannot read property 'push' of undefined

Does something seem to be leaking to me or is there a mistake on Babel's side?

Project react structure:

+ Root/
    + src/
        - App.js
        - index.js
        + pages/
            - MyComponent.js
    

This has changed in v6, useHistory is now useNavigate and we can use it as follows:

instead of:

const history = useHistory()
history.push('/')

we now use:

const navigate = useNavigate()
navigate('/')

You can't just use the useHistory hook to redirect to another page. You need to properly set up your application in order to use React Router. Look at their examples starting from this https://reactrouter.com/web/example/basic

You need to wrap your entire application with <BrowserRouter /> which will give the history object you are looking for through the hook.

By the way, you don't give a relative file path to history.push as an argument, you must give a valid route that you typically setup using <Route /> component

使用history.replace('/<route-name>')也可以。

you need to use it with react-router-dom. set your router config and then push it to that path. you can get more information by looking at documentation.

https://reactrouter.com/web/example/route-config

do not forget to set your switch components and your exact for root path.

When you are applying history.push, is that your path name? history.push('/pathname') is the process I guess. You can see here: https://reactrouter.com/web/api/Hooks

Using React 17.0>, this works for me:

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

const history = useHistory();
history.push("/home");

I've reached too much to find this correctly use of the useHistory function. Try and answer this post for feedback.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM