reactjs 使用吐司时钩子调用无效

jvidinwx  于 2023-04-29  发布在  React
关注(0)|答案(1)|浏览(114)

当在我的操作中使用吐司(脉轮UI)时,我最终得到了invalid hook call,并且查看了他们的docs并没有告诉我它可能是什么。我确实偶然发现了这个问题Invalid Hook Call - React Hooks,但我不确定这是否适用于我(?))

代码:

import { useToast } from "@chakra-ui/react";

export const action = async ({ request }) => {
  const toast = useToast(); // --> causes the failure
  //fetches, await and promise on this line 
  return redirect("test/completed");
};

我从main中的createBrowserRouter调用该操作。jsx

fjnneemd

fjnneemd1#

当你阅读有关钩子的规则时,我可以提供一个简单的例子:

import { useToast } from "@chakra-ui/react";

export const action = () => {
    // action is a normal javascript function we can't use hooks here
    //fetches, await and promise on this line 
    return true;
};

然后你可以去main.jsx任何使用它:

export const main = () => {
    // main is a functional component so it's okay to use hooks inside it
    const toast = useToast();
    

    // simple example to use toast depending on your action value
    const handleFetch = () => {
        const actionValue = action();
        if(actionValue) {
            toast({
                title: 'toast'
            })
        }
    }
    return( <div>I'm a functional component!</div> );
}

相关问题