gpt4 book ai didi

reactjs - 无法调用 useParams 钩子(Hook)

转载 作者:行者123 更新时间:2023-12-03 08:11:04 25 4
gpt4 key购买 nike

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

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>
)

}

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

最佳答案

Fetchevent箭头函数中删除useParams,react不会将箭头函数识别为react函数,将其直接放在顶层,如 useState 你有。钩子(Hook)的规则之一是你不应该在 nexted 函数中使用钩子(Hook),这就是问题的根源。您的代码应该如下所示

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>
)

关于reactjs - 无法调用 useParams 钩子(Hook),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70826319/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com