如何解决此问题 TypeError: Cannot read property 'location' of undefined?

时间:2021-03-03 05:58:50

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

我正在成功部署


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 文件,我在我的 repo 中没有看到这个文件:

如果我查看 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,有人可以帮我看看是什么问题或我哪里出错了吗?

2 个答案:

答案 0 :(得分:2)

    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 的路由器中

答案 1 :(得分:1)

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

return useContext(Context)?.location;