修复 React 的 Cannot read property ‘pathname’ of undefined错误
当我们没有在 React router 的 Link 组件上设置 to prop 时,会出现错误“Cannot read property ‘pathname’ of undefined”。 要解决错误,需要将链接上的 to
属性设置为特定路径,例如 <Link to="/">首页</Link>
。
这是在 React 路由中使用 Link 组件的最小示例。
import React from 'react';
// ?️ import Routes instead of Switch ?️
import {Route, Link, Routes} from 'react-router-dom';
export default function App() {
return (
<div>
<div>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
</ul>
</nav>
<Routes>
<Route path="/about" element={<About />} />
<Route path="/" element={<Home />} />
</Routes>
</div>
</div>
);
}
function Home() {
return <h2>Home</h2>;
}
function About() {
return <h2>About</h2>;
}
如果在测试使用 React 路由的页面时遇到错误,要确保在路由器组件上设置 location
属性而不是历史记录。
import {render} from '@testing-library/react';
import App from './App';
import {Router} from 'react-router-dom';
import {createMemoryHistory} from 'history';
test('renders react component', async () => {
const history = createMemoryHistory();
render(
<Router location={history.location} navigator={history}>
<App />,
</Router>,
);
expect(screen.getByText(/you are home/i)).toBeInTheDocument();
});
如果尝试访问路径名,需要使用 useLocation 钩子。
import React from 'react';
import {Route, Link, Routes, useLocation} from 'react-router-dom';
export default function App() {
// ?️ 使用 React 路由
const location = useLocation();
console.log('hash', location.hash);
console.log('pathname', location.pathname);
console.log('search', location.search);
return (
<div>
<div>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
</ul>
</nav>
<Routes>
<Route path="/about" element={<About />} />
<Route path="/" element={<Home />} />
</Routes>
</div>
</div>
);
}
function Home() {
return <h2>Home</h2>;
}
function About() {
return <h2>About</h2>;
}
确保将我们的应用程序封装在 index.js 文件中的 Router 组件中。
import {createRoot} from 'react-dom/client';
import App from './App';
import {BrowserRouter as Router} from 'react-router-dom';
const rootElement = document.getElementById('root');
const root = createRoot(rootElement);
// 在 Router 中封装 App
root.render(
<Router>
<App />
</Router>
);
用 Router 组件封装 React 应用程序的最佳位置是在 index.js 文件中,因为这是 React 应用程序的入口点。
一旦你的整个应用被一个 Router 组件包裹,你就可以在你的组件中的任何地方使用来自 React router 包的任何钩子。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。