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

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

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

import React, { useRef, useState } from "react";

function useStateAsync (value, isProp = false) {
  const ref = useRef(value);
  const [, forceRender] = useState(false);

  function updateState (newState) {
      if (!Object.is(ref.current, newState)) {
          ref.current = newState;
          forceRender(s => !s);
      }
  }

  if (isProp) {
      ref.current = value;
      return ref;
  }

  return [ref, updateState];
}

function genInterval(myFunc) {
  var intervalId = setInterval(() => {
    myFunc()}, 1000) // ---------- IT THROWS THE ERROR ------------------
                     // I'm guessing that it knows myFunc due to closures
  return intervalId
}

function Counter() {
  const [count, setCount] = useStateAsync(0);
  const [intervalid, setIntervalId] = useState(0)

  function theFunc() {
    setCount(count.current++)
  }

  return (
    <div>
      <button
        onClick={() => {
          setIntervalId(genInterval(theFunc))
        }}
      >
        Start interval
      </button>     
      <button
        onClick={() => {
          clearInterval(intervalid)
        }}
      >
        Stop interval
      </button>
      <button
        onClick={() => {
          console.log(count.current)
        }}
      >
        Console log
      </button>
      <p>The counter is now {count.current}</p>
    </div>
  );
}
im9ewurl

im9ewurl1#

试着换一个新的

setIntervalId(genInterval(theFunc))

具有

setIntervalId(genInterval(() => theFunc()))

相关问题