
JS
React JS:错误:useLocation() 只能在
Javascriptimport React from 'react';import { BrowserRouter, Link, Route, Switch, useLocation } from 'react-router-dom';const Home = () => { const location = useLocation(); return ( <div> <h1>Home Page</h1> Current URL: {location.pathname}
</div> );};const About = () => { const location = useLocation(); return ( <div> <h1>About Page</h1> <img src="https://img.izhida.com/topic/d52387880e1ea22817a72d3759213819.jpg" alt="Java"><br>Java
Current URL: {location.pathname} </div> );};const App = () => { return ( <BrowserRouter> <nav> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/about">About</Link> </li> </ul> </nav> <Switch> <Route path="/" exact component={Home} /> <Route path="/about" component={About} /> </Switch> </BrowserRouter> );};export default App;在这个例子中,我们创建了一个简单的React应用程序,包含了两个页面:Home和About。我们使用了useLocation()钩子来获取当前页面的URL信息,并将其显示在页面上。然而,如果我们忘记将这些组件包裹在Javascriptconst App = () => { return ( <BrowserRouter> {/* 省略其他代码 */} <Switch> {/* 省略其他代码 */} </Switch> </BrowserRouter> );};解决useLocation()只能在Javascriptimport React from 'react';import { BrowserRouter, Link, Route, Switch, useLocation } from 'react-router-dom';const Home = () => { const location = useLocation(); return ( <div> <h1>Home Page</h1> Current URL: {location.pathname}
</div> );};const About = () => { const location = useLocation(); return ( <div> <h1>About Page</h1> Current URL: {location.pathname}
</div> );};const App = () => { return ( <BrowserRouter> <nav> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/about">About</Link> </li> </ul> </nav> <Switch> <Route path="/" exact component={Home} /> <Route path="/about" component={About} /> </Switch> </BrowserRouter> );};export default App;在这个例子中,我们将组件包裹在Copyright © 2025 IZhiDa.com All Rights Reserved.
知答 版权所有 粤ICP备2023042255号