首页 > 解决方案 > React TypeScript 16.8 如何向 useEffect() 添加依赖项

问题描述

在 useEffect() 中,我创建了一些键,然后尝试调用不在 useEffect() 块中的函数 addKeysToState() 并导致错误。

我尝试在 useEffect() 末尾将 'addKeysToState' 和 addKeysToState() 添加到数组中,但无济于事。

我得到的错误是......

React Hook useEffect has a missing dependency: 'addKeysToState'. Either include it or remove the dependency array react-hooks/exhaustive-deps

代码片段...

const FeedbackForm: React.FC<props> = ({publicKey}) => {
  const [formState, setState] = useState();

  useEffect(() => {
    const genRandomKey = async () => {
      const tempPrivateKey = await ecc.randomKey();
      if (tempPrivateKey) {
        const tempPublicKey = await ecc.privateToPublic(tempPrivateKey);
        if (tempPublicKey) {
          addKeysToState(tempPrivateKey, tempPublicKey);
        }
      }
    };
    genRandomKey();
  }, []);

  const addKeysToState = (tempPrivateKey: string, tempPublicKey: string) => {
              setState({ 
            ...formState, 
            tempPrivateKey,
            tempPublicKey,
          })
  }

标签: reactjs

解决方案


addKeysToState放在钩子里面怎么样?看起来它不是依赖项,而是实现细节。

请注意,由于addKeysToState使用先前的状态,我们应该使用回调形式来代替,以避免竞争条件。

const FeedbackForm: React.FC<props> = ({publicKey}) => {
  const [formState, setState] = useState();

  useEffect(() => {
    const addKeysToState = (tempPrivateKey: string, tempPublicKey: string) => setState((prevState) => ({ 
     ...prevState, 
     tempPrivateKey,
     tempPublicKey,
   ))
    const genRandomKey = async () => {
      const tempPrivateKey = await ecc.randomKey();
      if (tempPrivateKey) {
        const tempPublicKey = await ecc.privateToPublic(tempPrivateKey);
        if (tempPublicKey) {
          addKeysToState(tempPrivateKey, tempPublicKey);
        }
      }
    };
    genRandomKey();
  }, []);

推荐阅读