您可以使用以下方式强制重新渲染错误边界,
首先制作一个单独的功能组件来保存错误边界并将监听器添加到历史记录
import { createBrowserHistory } from "history";
const history = createBrowserHistory();
//a fallback component
const ErrorFallback = () => {
return <>
<h1>Something went wrong.</h1>
<button onClick={() => {
history.back();
}}>go back </button>
</>
}
function RoutesContainer() {
const [update, setUpdate] = useState(false);
let navigate = useNavigate();
const historyChange = () => {
if (window.location.pathname !== history.location.pathname) {
navigate(window.location.pathname, { replace: true });
}
};
useEffect(() => {
history.listen(historyChange)
}, [historyChange])
return <ErrorBoundary key={window.location.pathname} FallbackComponent={ErrorFallback}>
<Routes>
<Route path="/page1" element={<Page1 PageName="Page1" />} />
<Route path="/page2" element={<Page2 PageName={{}} />} />
</Routes>
</ErrorBoundary>
}
当你从page2回到page1的时候,history.location.pathname会有值“page2”,因为你按回,这个值将不匹配window.location.pathname,因为window.location.pathname有值“page1”,在这个阶段,我们将导航到 window.location.pathname,并使用这个值作为我们错误边界组件中的键。在写这个答案的时候,我使用 react-router-dom V6 和 react v18
一个完整的用例演示在这里
import React, { useEffect, useState } from 'react';
import { BrowserRouter, Link, Route, Routes } from 'react-router-dom';
import { createBrowserHistory } from "history";
import { useNavigate } from "react-router-dom";
import { ErrorBoundary } from 'react-error-boundary'
const history = createBrowserHistory();
const ErrorFallback = () => {
return <>
<h1>Something went wrong.</h1>
<button onClick={() => {
history.back();
}}>go back </button>
</>
}
const Page1 = ({ PageName }) => {
return (<p>{PageName}
<Link to={'/page2'} >page 2</Link>
</p>)
}
const Page2 = ({ PageName }) => {
return (<p>{PageName}</p>)
}
function RoutesContainer() {
const [update, setUpdate] = useState(false);
let navigate = useNavigate();
const historyChange = () => {
if (window.location.pathname !== history.location.pathname) {
navigate(window.location.pathname, { replace: true });
}
};
useEffect(() => {
history.listen(historyChange)
}, [historyChange])
return <ErrorBoundary key={window.location.pathname} FallbackComponent={ErrorFallback}>
<Routes>
<Route path="/page1" element={<Page1 PageName="Page1" />} />
<Route path="/page2" element={<Page2 PageName={{}} />} />
</Routes>
</ErrorBoundary>
}
function App() {
return (
<BrowserRouter><RoutesContainer /></BrowserRouter>
);
}
export default App;