【问题标题】:Cannot read property 'location' of undefined (useLocation())无法读取未定义的属性“位置”(useLocation())
【发布时间】:2021-08-02 19:19:27
【问题描述】:

当我尝试使用 useLocation() 时出现此错误:TypeError: Cannot read property 'location' of undefined。我完美地从 react-router-dom 导入 useLocation 但发生了这个错误。我该如何解决?

import React, { createContext, useEffect, useState } from 'react';
import { Route, Switch, useLocation } from 'react-router-dom';
import { getCurrentUser, handleSignOut } from './components/login/HandleLogin';
import Login from './components/login/Login';
import Booking from './components/booking/Booking';
import Header from './components/shared/header/Header';
import Home from './components/home/Home';
import PrivateRoute from './components/privateRoute/PrivateRoute';
import Search from './components/search/Search';

export const UserContext = createContext();
function App() {
  const location = useLocation();
  const [user, setUser] = useState(null);
  const [bookingInfo, setBookingInfo] = useState({});
  useEffect(() => {
    getCurrentUser().then(res => {
      setUser(res)
    })
  }, [])
  const signOUtUser = () => {
    handleSignOut().then(res => {
      setUser(res)
    })
  }
  return (
    <UserContext.Provider value={{ user, setUser, bookingInfo, setBookingInfo, signOUtUser }}>
      <div className={`${location.pathname === '/' || location.pathname.includes('booking') ? "home" : ""}`}>
        <Header />
        <Switch>
          <Route exact path="/" component={Home} />
          <Route path="/booking/:id" component={Booking} />
          <PrivateRoute path="/search/:id">
            <Search />
          </PrivateRoute>
          <Route path="/login" component={Login} />
        </Switch>
      </div>
    </UserContext.Provider>
  );
}

export default App;

显示错误位置未定义。

【问题讨论】:

  • 您是否尝试过安慰您要声明的位置常量?这是否也会让您返回 undefined ?
  • 当位置未定义时不要渲染任何东西,因为你的组件依赖于它
  • @bel3atar 明白了。谢谢
  • 可能是来自here的重复问题

标签: javascript reactjs


【解决方案1】:

使用 BrowserRouter .

import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link
} from "react-router-dom";

【讨论】:

    猜你喜欢
    • 2021-12-20
    • 2017-08-26
    • 1970-01-01
    • 2021-12-12
    • 2022-07-06
    • 2020-12-22
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    相关资源
    最近更新 更多