Как я могу имитировать нажатие кнопки «назад» в браузере из кода?
const history = useHistory()
history.goBack()
Я знаю, что я тоже могу это сделать, но, как я понял, в новых версиях react-router-dom useHistory был изменен на useNavigate, в котором нет функции goBack(). Как я могу вернуться на последнюю страницу, не откатывая react-router-dom?
...in the new versions of
react-router-dom
useHistory
was changed touseNavigate
, which has nogoBack()
function.
Это не совсем точно. В react-router-dom@6
крючок useHistory
был заменены к крючку useNavigate
. Хук useNavigate
возвращает navigate
функцию вместоhistory
объект с методами навигации.
declare function useNavigate(): NavigateFunction; interface NavigateFunction { ( to: To, options?: { replace?: boolean; state?: any } ): void; (delta: number): void; }
В дальнейшем
The navigate function has two signatures:
- Either pass a To value (same type as ) with an optional second { replace, state } arg or
- Pass the delta you want to go in the history stack. For example, navigate(-1) is equivalent to hitting the back button.
Вы хотите использовать аргумент delta
. Если вы помните из RRDv4/5, что history.goBack()
эквивалентно history.go(-1)
.
// Go back to the previous history entry. The following // two lines are synonymous. history.go(-1); history.goBack();
How can I go back to the last page without rolling back
react-router-dom
?
В react-router-dom@6
выдать обратную навигацию, т.е. POP:
const navigate = useNavigate();
navigate(-1);