javascript—我将函数作为参数发送,但它会抛出一个错误

voj3qocg  于 2021-09-08  发布在  Java
关注(0)|答案(1)|浏览(407)

有人能告诉我为什么它说myfunc不是一个函数吗?

  1. import React, { useRef, useState } from "react";
  2. function useStateAsync (value, isProp = false) {
  3. const ref = useRef(value);
  4. const [, forceRender] = useState(false);
  5. function updateState (newState) {
  6. if (!Object.is(ref.current, newState)) {
  7. ref.current = newState;
  8. forceRender(s => !s);
  9. }
  10. }
  11. if (isProp) {
  12. ref.current = value;
  13. return ref;
  14. }
  15. return [ref, updateState];
  16. }
  17. function genInterval(myFunc) {
  18. var intervalId = setInterval(() => {
  19. myFunc()}, 1000) // ---------- IT THROWS THE ERROR ------------------
  20. // I'm guessing that it knows myFunc due to closures
  21. return intervalId
  22. }
  23. function Counter() {
  24. const [count, setCount] = useStateAsync(0);
  25. const [intervalid, setIntervalId] = useState(0)
  26. function theFunc() {
  27. setCount(count.current++)
  28. }
  29. return (
  30. <div>
  31. <button
  32. onClick={() => {
  33. setIntervalId(genInterval(theFunc))
  34. }}
  35. >
  36. Start interval
  37. </button>
  38. <button
  39. onClick={() => {
  40. clearInterval(intervalid)
  41. }}
  42. >
  43. Stop interval
  44. </button>
  45. <button
  46. onClick={() => {
  47. console.log(count.current)
  48. }}
  49. >
  50. Console log
  51. </button>
  52. <p>The counter is now {count.current}</p>
  53. </div>
  54. );
  55. }
im9ewurl

im9ewurl1#

试着换一个新的

  1. setIntervalId(genInterval(theFunc))

具有

  1. setIntervalId(genInterval(() => theFunc()))

相关问题