【问题标题】:how can i fix use location error in my react app?如何修复我的反应应用程序中的使用位置错误?
【发布时间】:2021-12-24 05:39:10
【问题描述】:

从“样式组件”导入样式;从“../componant/Navbar”导入导航栏;从“../componant/Announcement”导入公告;从“../componant/Products”导入产品;从“../componant/Newsletter”导入时事通讯;从“../componant/Footer”导入页脚;从“../responsive”导入{ mobile };从“反应路由器”导入 { useLocation };从“反应”导入 { useState };

const Container = styled.div``;

const Title = styled.h1 margin: 20px;;

const FilterContainer = styled.div display: flex; justify-content: space-between;;

const Filter = styled.div margin: 20px; ${mobile({ width: "0px 20px", display: "flex", flexDirection: "column" })};

const FilterText = styled.span font-size: 20px;字体粗细:600;右边距:20px; ${mobile({ marginRight: "0px" })};

const Select = styled.select padding: 10px;右边距:20px; ${mobile({ 边距: "10px 0px" })}; const Option = styled.option``;

const ProductList = () => { const location = useLocation(); const cat = location.pathname.split("/")[2]; const [过滤器,setFilters] = useState({}); const [sort, setSort] = useState("newest");

const handleFilters = (e) => { const value = e.target.value; setFilters({ ...filters, [e.target.name]: value, }); };

return ( {cat} 过滤产品:颜色 白色 黑色 红色 蓝色 黄绿色 尺寸 XS SML XL 排序产品:

导出默认产品列表;

【问题讨论】:

  • 错误:useLocation() 只能在 组件的上下文中使用。不变 C:/Users/hp/packages/react-router/index.tsx:19 16 |导出类型 { 位置、路径、到、导航类型 }; 17 | 18 |函数不变量(条件:任意,消息:字符串):断言条件 { > 19 | if (!cond) throw new Error(message); 20 | 21 | 22 |功能警告(条件:任何,消息:字符串):无效{查看编译的useLocation C:/Users/hp/packages/react-router/index.tsx:397 394 | * @see reactrouter.com/docs/en/v6/api#uselocation 395 |
  • 错误:useLocation() 只能在 组件的上下文中使用。不变 C:/Users/hp/packages/react-router/index.tsx:19 16 |导出类型 { 位置、路径、到、导航类型 }; 17 | 18 |函数不变量(条件:任意,消息:字符串):断言条件 { > 19 | if (!cond) throw new Error(message); 20 | }

标签: reactjs


【解决方案1】:

将您的应用包装在Routes 组件中。

import React from "react";
import {
  BrowserRouter as Router,
  Routes,
} from "react-router-dom";


const AppWrapper = () => {
  return (
    <Router>
      <Routes>
        <App />
      </Routes>
    </Router>
  );
};

export default AppWrapper;

【讨论】:

  • 我试过了,但是没用
  • @GaethOmari 你尝试了什么?请提供您尝试过的代码
  • 从“./pages/Product”导入产品;从“./pages/Home”导入主页;从“./pages/ProductList”导入产品列表;从“./pages/Register”导入注册;从“./pages/Login”导入登录;从“./pages/Cart”导入购物车从“react-redux”导入{ useSelector};3。 import { BrowserRouter as Router, Switch, Route, Redirect, } from "react-router-dom";
  • const App = () => { const user = true return ( Route> {user ? : } {user ? : }
  • ); };导出默认应用;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-08-17
  • 2019-08-29
  • 2020-11-29
  • 1970-01-01
  • 2020-02-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多