返回一个React钩子中的函数会产生意外的结果。

huangapple go评论70阅读模式
英文:

Returning a function in a React hook giving unexpected result

问题

I'm trying to create a React hook that returns a function that users of the hook will invoke. The hook creates a function inside the hook.

以下是翻译好的部分:
我正在尝试创建一个React钩子,该钩子返回一个函数,使用该钩子的用户将调用该函数。这个钩子在内部创建一个函数。

英文:

I'm trying to create a React hook that returns a function that users of the hook will invoke. The hook creates a function inside the hook.

Here's a minimal example

// fetch.js

import { useEffect, useState} from "react";

export const useFetch = () => {
  
  const [fn, setFn] = useState(null);

  useEffect(() => {
    const fn_ = () => console.log("test")
    setFn(fn_)
  }, []);

  return fn;
}
// App.js

import { useFetch } from './fetch';

function App() {
  const fn = useFetch()
  
  return (
    <div className="App">
      hello
    </div>
  );
}

I have the Strict mode disabled as well.

// index.js

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <App />
);

Even though I'm not invoking fn(), I see it getting executed and console log output.

返回一个React钩子中的函数会产生意外的结果。

Any idea why this is happening? Pretty sure I'm doing something wrong but can't figure out what.

Edit:

Thanks for the answer below. Found this explained in React FAQ https://react.dev/reference/react/useState#im-trying-to-set-state-to-a-function-but-it-gets-called-instead

答案1

得分: 2

问题在于将函数传递给状态设置器,它假设您正在使用功能性更新

如我在上面的注释中所说,效果钩子和状态是完全多余的,尤其不应该用于函数。

export const useFetch = () => () => console.log("[useFetch] test");
英文:

The problem with passing a function to a state setter is it assumes you're using a functional update.

Like I said in the comments above, the effect hook and state are totally redundant and you should especially not use it for a function

export const useFetch = () => () => console.log("[useFetch] test");

huangapple
  • 本文由 发表于 2023年4月20日 10:25:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76060081.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定