【问题标题】:Cannot call useParams hook无法调用 useParams 挂钩
【发布时间】:2022-01-25 04:30:22
【问题描述】:

我试图在我的 React 函数之一中使用 useParams() 钩子,但它给出了以下错误

Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a 
function component. This could happen for one of the following reasons: 
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app

我试图调用 useParams() 的 React 组件看起来像这样

const IndividualEvent = () => {
const [showError, setShowError] = useState(false);
const [event, setEvent] = useState(null);
const [showLoader, setShowLoader] = useState(true);

const Fetchevent = () => {
    const {eventName} = useParams();
    alert(eventName);
}

useEffect(() => {
    Fetchevent();
})

return (
    <div id="individual-event">
        {
            showLoader ? <Loader text='Fetching event details'/> : null
        }
        <Sidebar />
        <div id="event-container" className="page">

        </div>
    </div>
)

}

这里的错误是什么以及如何解决它

【问题讨论】:

标签: reactjs react-hooks react-router frontend


【解决方案1】:

Fetchevent箭头函数里面去掉useParams,react不把箭头函数识别为react函数,直接放到顶层,就像你有的useState一样。钩子的规则之一是你不应该在 nexted 函数中使用钩子,这就是问题所在。你的代码应该是这样的

const IndividualEvent = () => {
const [showError, setShowError] = useState(false);
const [event, setEvent] = useState(null);
const [showLoader, setShowLoader] = useState(true);
const {eventName} = useParams(); // this line was moved here

const Fetchevent = () => {
    alert(eventName);
}

useEffect(() => {
    Fetchevent();
})

return (
    <div id="individual-event">
        {
            showLoader ? <Loader text='Fetching event details'/> : null
        }
        <Sidebar />
        <div id="event-container" className="page">

        </div>
    </div>
)

【讨论】:

    【解决方案2】:

    您可能正在使用尚不支持 Hooks 的 react-dom (react-native (

    npm ls react-dom
    

    npm ls react
    

    在您的应用程序文件夹中检查您正在使用的版本。如果您发现其中不止一个,这也可能会产生问题。 如果看到不止一个,可以通过添加一些日志并重新启动开发服务器来调试此问题:

    // Add this in node_modules/react-dom/index.js
    window.React1 = require('react');
    
    // Add this in your component file
    require('react-dom');
    window.React2 = require('react');
    console.log(window.React1 === window.React2);
    

    如果它打印false,那么你可能有两个 React,需要弄清楚为什么会发生这种情况。

    This issue 包含了社区遇到的一些常见原因。

    【讨论】:

    • 这是一个错误的答案 - 显然 OP 违反了钩子规则并试图在 useEffect 内调用 Fetchevent,但 Fetchevent,因为它在其中使用了一个钩子,所以根据定义本身就是一个钩子
    • ...但在一般情况下,这将是一个很好的建议。所以继续帮助其他人!
    猜你喜欢
    • 1970-01-01
    • 2021-12-07
    • 1970-01-01
    • 2022-06-12
    • 1970-01-01
    • 1970-01-01
    • 2020-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多