useLocation:钩子只能在函数组件体内调用

use*_*702 5 reactjs react-router react-hooks

我正在尝试在我的函数组件中使用useLocation钩子,但我得到了Error: Invalid hook call. Hooks can only be called inside of the body of a function component..

我的应用程序的结构如下:

import React, {useEffect, useState} from "react";
import Navigation from "./components/Navigation";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";

function App() {
    // ...
    return (
        <Router>
            <div>
                // ...
                <Navigation themes={themes} />
                // ...
                <Switch>
                    <Route path="/mytheme">
                        <MyTheme />
                    </Route>
                </Switch>
            </div>
        </Router>
    );
}

export default App;
Run Code Online (Sandbox Code Playgroud)

组件Navigation(见上文)如下所示:

import React from "react";
import { Link, useLocation } from "react-router-dom";

function Navigation(props) {
    const location = useLocation(); // ---> this is the problem
    return (
        <div>
            {
                props.themes.map((theme, index) => {
                    return <Link key={index} to={"/" + theme.id}>
                        { theme.name }
                    </Link>
                })
            }
        </div>
    );
}

export default Navigation;
Run Code Online (Sandbox Code Playgroud)

useLocation导航工作正常,但我想在组件中使用Navigation来突出显示活动的“页面”。

Saf*_*thi -2

对于任何人都可能面临这个愚蠢的错误,我有同样的错误,因为我的函数组件名称是“index”。对我来说,只需更改组件的名称即可解决问题。