如何在不重新渲染整个应用程序的情况下更新 URL 并替换 React Router v5 中的历史状态?

How to update the URL and replace history state in React Router v5 without re-rendering the whole app?

在使用 React Router 及其浏览器历史记录时,有几种情况会触发重新渲染,我希望在不重新渲染整个应用程序的情况下这样做:

有没有办法做到这一点,或者解决方案是优化某些组件以提高性能?

您可以这样使用 history.replaceState()

const setQueryParams = (param, value) => {
    const history = window.history;
    let currentUrlParams = new URLSearchParams(window.location.search);
    currentUrlParams.set(param, value);

    const url = `${window.location.pathname}?${currentUrlParams.toString()}`;
    history.replaceState({}, '', url);
};