为什么我在函数中调用它时会收到错误无效的钩子调用

时间:2021-02-02 10:26:04

标签: reactjs react-redux react-hooks

我有一个在多个组件上调用的函数,我想把它放在这样的帮助文件中:

import { useDispatch } from "react-redux";
import { quoteActions } from "../../_actions";
export const nextScreen = () => {
  const dispatch = useDispatch();
  dispatch(quoteActions.nextStep());
  dispatch(quoteActions.disableContinue(true));
};

然后当我进入一个必须使用该功能的组件时:

import {nextScreen} from '../helpers/';
function Screen1(props){
 useEffect(()=>{
   props.ref.current.addEventListener("click",nextScreen);
   return ()=> props.ref.current.removeEventListener("click",nextScreen);
},[])
 return(
  ...
)
}

如果我在 Screen1 组件中声明 nextScreen 它可以工作,但如果我把它放在一个单独的文件中就不行,为什么? 我尝试在我声明为 nextScreen 的文件中导入 React 但它没有修复它,也尝试返回 null

1 个答案:

答案 0 :(得分:1)

使用钩子的函数(如 useDispatch)称为 custom hooks,您需要添加 use 前缀以帮助 linter 检查 Rules Of Hooks 违规。

export const useNextScreen = () => { ... };

除了错误之外,这段代码将不起作用,因为您必须在顶层调用钩子,逻辑应该是:

import { nextScreen } from "../helpers/";
function Screen1(props) {
  const dispatch = useDispatch();

  useEffect(() => {
    const nextScreen = () => {
      dispatch(quoteActions.nextStep());
      dispatch(quoteActions.disableContinue(true));
    };
    props.ref.current.addEventListener("click", nextScreen);
    return () => props.ref.current.removeEventListener("click", nextScreen);
  }, [dispatch]);
  return <></>;
}