我发送一个函数作为参数,但它抛出一个错误
I'm sending a function as a parameter, but it throws an error
有人能告诉我为什么它说 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>
);
}
尝试更换
setIntervalId(genInterval(theFunc))
和
setIntervalId(genInterval(() => theFunc()))
有人能告诉我为什么它说 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>
);
}
尝试更换
setIntervalId(genInterval(theFunc))
和
setIntervalId(genInterval(() => theFunc()))