【问题标题】:How do I fix this issue TypeError: Cannot read property 'location' of undefined?如何解决此问题 TypeError:无法读取未定义的属性“位置”?
【发布时间】:2021-03-03 05:58:50
【问题描述】:

我正在成功部署


useLocation
/Users/hvaandres/Desktop/Development/Ecommerce/modules/hooks.js:29
  26 |     );
  27 |   }
  28 | 
> 29 |   return useContext(Context).location;
  30 | }
  31 | 
  32 | export function useParams() {

成功:


Compiled successfully!

You can now view ecommerce-store in the browser.

  Local:            http://localhost:3000
  On Your Network:  http://192.168.1.194:3000

Note that the development build is not optimized.
To create a production build, use npm run build.

这个问题来自一个 hook.js 文件,我在我的仓库中没有看到这个文件:

如果我查看 chrome 工具,这是我的问题的参考


import React from "react";
import invariant from "tiny-invariant";

import Context from "./RouterContext.js";
import HistoryContext from "./HistoryContext.js";
import matchPath from "./matchPath.js";

const useContext = React.useContext;

export function useHistory() {
  if (__DEV__) {
    invariant(
      typeof useContext === "function",
      "You must use React >= 16.8 in order to use useHistory()"
    );
  }

  return useContext(HistoryContext);
}

export function useLocation() {
  if (__DEV__) {
    invariant(
      typeof useContext === "function",
      "You must use React >= 16.8 in order to use useLocation()"
    );
  }

  return useContext(Context).location;
}

export function useParams() {
  if (__DEV__) {
    invariant(
      typeof useContext === "function",
      "You must use React >= 16.8 in order to use useParams()"
    );
  }

  const match = useContext(Context).match;
  return match ? match.params : {};
}

export function useRouteMatch(path) {
  if (__DEV__) {
    invariant(
      typeof useContext === "function",
      "You must use React >= 16.8 in order to use useRouteMatch()"
    );
  }

  const location = useLocation();
  const match = useContext(Context).match;

  return path ? matchPath(location.pathname, path) : match;
}

如果我跟踪问题,它似乎位于调用 useLocation() 的 NavBar.js 内部:


import React, { useState } from 'react';
import { AppBar, Toolbar, IconButton, Badge, MenuItem, Menu, Typography } from '@material-ui/core';
import { ShoppingCart } from '@material-ui/icons';
import { Link, useLocation } from 'react-router-dom';

import logo from '../../assets/logo.png';
import useStyles from './styles';

const PrimarySearchAppBar = ({ totalItems }) => {
  const [mobileMoreAnchorEl, setMobileMoreAnchorEl] = useState(null);
  const classes = useStyles();
  const location = useLocation();

  const isMobileMenuOpen = Boolean(mobileMoreAnchorEl);

  const handleMobileMenuClose = () => setMobileMoreAnchorEl(null);

  const mobileMenuId = 'primary-search-account-menu-mobile';

  const renderMobileMenu = (
    <Menu anchorEl={mobileMoreAnchorEl} anchorOrigin={{ vertical: 'top', horizontal: 'right' }} id={mobileMenuId} keepMounted transformOrigin={{ vertical: 'top', horizontal: 'right' }} open={isMobileMenuOpen} onClose={handleMobileMenuClose}>
      <MenuItem>
        <IconButton component={Link} to="/cart" aria-label="Show cart items" color="inherit">
          <Badge badgeContent={totalItems} color="secondary">
            <ShoppingCart />
          </Badge>
        </IconButton>
        <p>Cart</p>
      </MenuItem>
    </Menu>
  );

  return (
    <>
      <AppBar position="fixed" className={classes.appBar} color="inherit">
        <Toolbar>
          <Typography component={Link} to="/" variant="h6" className={classes.title} color="inherit">
            <img src={logo} alt="commerce.js" height="25px" className={classes.image} /> Commerce.js
          </Typography>
          <div className={classes.grow} />
          {location.pathname === '/' && (
          <div className={classes.button}>
            <IconButton component={Link} to="/cart" aria-label="Show cart items" color="inherit">
              <Badge badgeContent={totalItems} color="secondary">
                <ShoppingCart />
              </Badge>
            </IconButton>
          </div>
          )}
        </Toolbar>
      </AppBar>
      {renderMobileMenu}
    </>
  );
};

export default PrimarySearchAppBar;

问题是我不知道自己做错了什么。这是我的repo,有人可以帮我看看是什么问题或我在哪里犯了错误?

【问题讨论】:

  • 您需要发布有关代码的更多详细信息,而不仅仅是链接到您的 github 存储库并期望人们浏览所有内容。
  • 我还应该在这里发布什么,因为这是我收到的唯一错误消息?
  • 首先是完整的堆栈跟踪,所以我知道错误来自你的代码中的哪个位置
  • 那么问题就在那里,如果你注意第一行,你会看到下面的内容:“/Users/hvaandres/Desktop/Development/Ecommerce/modules/hooks.js: 29" 但是,我的仓库中没有该文件
  • 对。因为那是一个 react-router 文件。问题似乎是您在代码中某处或以不正确的方式调用useLocation()。堆栈跟踪中应该列出更多文件,显示调用它的位置。

标签: javascript node.js reactjs testing e-commerce


【解决方案1】:
    in App.js
 import { BrowserRouter as Router} from "react-router-dom";
    then wrap your components inside Router
    
         <Router>
          <Navbar  totalItems={cart.total_items}/>
          {/* <Products products={products} onAddToCart={handleAddToCart}/> */}
          <Cart cart={cart}/>
          </Router>

这肯定会解决您的问题,因为您的组件正在尝试使用来自 useLocation() 的位置,因此您必须将组件包装在来自 router-dom 的路由器中

【讨论】:

    【解决方案2】:

    尝试使用可选链。如果未定义,则不会抛出异常,而是返回未定义。

    return useContext(Context)?.location;
    

    【讨论】:

      猜你喜欢
      • 2018-12-21
      • 1970-01-01
      • 1970-01-01
      • 2022-01-01
      • 2020-05-09
      • 2020-07-24
      • 2017-07-26
      • 1970-01-01
      相关资源
      最近更新 更多