最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I fix this issue TypeError: Cannot read property 'location' of undefined? - Stack Overflow

programmeradmin0浏览0评论

I'm having a successful deployment


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

Success:


Compiled successfully!

You can now view emerce-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.

The issue says that is ing from a hook.js file which I don't see this file in my repo:

If I look at the chrome tools, this is the reference from my issue


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;
}

If I trace the problem it seems that is located inside of my NavBar.js which is invoking useLocation():


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 ponent={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 ponent={Link} to="/" variant="h6" className={classes.title} color="inherit">
            <img src={logo} alt="merce.js" height="25px" className={classes.image} /> Commerce.js
          </Typography>
          <div className={classes.grow} />
          {location.pathname === '/' && (
          <div className={classes.button}>
            <IconButton ponent={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;

The problem is that I don't know what I'm doing wrong. This is my repo, could someone help me to see what is the issue or where I'm making a mistake?

I'm having a successful deployment


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

Success:


Compiled successfully!

You can now view emerce-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.

The issue says that is ing from a hook.js file which I don't see this file in my repo:

If I look at the chrome tools, this is the reference from my issue


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;
}

If I trace the problem it seems that is located inside of my NavBar.js which is invoking useLocation():


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 ponent={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 ponent={Link} to="/" variant="h6" className={classes.title} color="inherit">
            <img src={logo} alt="merce.js" height="25px" className={classes.image} /> Commerce.js
          </Typography>
          <div className={classes.grow} />
          {location.pathname === '/' && (
          <div className={classes.button}>
            <IconButton ponent={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;

The problem is that I don't know what I'm doing wrong. This is my repo, could someone help me to see what is the issue or where I'm making a mistake?

Share Improve this question edited Mar 3, 2021 at 6:28 Hvaandres asked Mar 3, 2021 at 5:58 HvaandresHvaandres 1,0155 gold badges22 silver badges47 bronze badges 6
  • 1 You need to post more details on your code, not just link to your github repo and expect people to go through everything. – Nick Commented Mar 3, 2021 at 6:04
  • What else should I publish here since this is the only error message that I'm getting? – Hvaandres Commented Mar 3, 2021 at 6:06
  • to start with, the full stack trace so I know where in your code the error is ing from – Nick Commented Mar 3, 2021 at 6:08
  • Well the issue is there, if you pay attention to the first line, you will see that is saying the following: "/Users/hvaandres/Desktop/Development/Emerce/modules/hooks.js:29" However, I don't have that file anywhere inside of my repo – Hvaandres Commented Mar 3, 2021 at 6:14
  • Right. Because that's a react-router file. The problem appears to be that you are invoking useLocation() somewhere in your code in a place or in a way that is incorrect. There should be more files listed in the stack trace that show where this was called from. – samuei Commented Mar 3, 2021 at 6:22
 |  Show 1 more ment

2 Answers 2

Reset to default 5
    in App.js
 import { BrowserRouter as Router} from "react-router-dom";
    then wrap your ponents inside Router
    
         <Router>
          <Navbar  totalItems={cart.total_items}/>
          {/* <Products products={products} onAddToCart={handleAddToCart}/> */}
          <Cart cart={cart}/>
          </Router>

This will solve your problem for sure, as your ponent is triying to use location from useLocation(), for that you have to wrap your ponent inside a Router ing from router-dom

Try using optional chaining. If it's undefined then it will not throw an exception instead it will return undefined.

return useContext(Context)?.location;
发布评论

评论列表(0)

  1. 暂无评论