How to return to the original position after navigating in React?
In React, we can use the react-router-dom library to navigate between pages. To go back to the previous location, we can use the goBack method of the history object.
First, make sure your components are wrapped in the
import { useHistory } from 'react-router-dom';
function MyComponent() {
const history = useHistory();
const handleClick = () => {
history.goBack();
};
return (
<div>
<button onClick={handleClick}>返回</button>
</div>
);
}
In the example above, we used the useHistory hook to access the history object and call the goBack method to return to the original location when the button is clicked.
Please note: if there is no browsing history or if you are at the starting point of browsing history, the goBack method will not have any effect. So, before using the goBack method, it’s best to first check the length of the browsing history. For example:
import { useHistory } from 'react-router-dom';
function MyComponent() {
const history = useHistory();
const handleClick = () => {
if (history.length > 1) {
history.goBack();
} else {
// 处理无法返回的情况
}
};
return (
<div>
<button onClick={handleClick}>返回</button>
</div>
);
}
In this way, we can handle the situation based on the actual circumstances when we are unable to browse our browsing history or go back to a previous page.