javascript React Hooks useMemo useCallback
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript React Hooks useMemo useCallback相关的知识,希望对你有一定的参考价值。
import React, {
useState,
useRef,
useEffect,
useMemo,
useCallback
} from "react";
import Ball from "./Ball";
function getWinNumbers() {
console.log("getWinNumbers");
const candidate = Array(45)
.fill()
.map((v, i) => i + 1);
const shuffle = [];
while (candidate.length > 0) {
shuffle.push(
candidate.splice(Math.floor(Math.random() * candidate.length), 1)[0]
);
}
const bonusNumber = shuffle[shuffle.length - 1];
const winNumbers = shuffle.slice(0, 6).sort((p, c) => p - c);
return [...winNumbers, bonusNumber];
}
export default function Lotto() {
const lottoNumbers = useMemo(() => getWinNumbers(), []);
const [winNumbers, setWinNumbers] = useState(lottoNumbers);
const [winBalls, setWinBalls] = useState([]);
const [bonus, setBonus] = useState(null);
const [redo, setRedo] = useState(false);
const timeouts = useRef([]);
useEffect(() => {
for (let i = 0; i < winNumbers.length - 1; i++) {
timeouts.current[i] = setTimeout(() => {
setWinBalls(prevBalls => [...prevBalls, winNumbers[i]]);
}, (i + 1) * 1000);
}
timeouts.current[6] = setTimeout(() => {
setBonus(winNumbers[6]);
setRedo(true);
}, 7000);
return () => {
timeouts.current.forEach(v => {
clearTimeout(v);
});
};
}, [timeouts.current]);
const onClickRedo = useCallback(() => {
setWinNumbers(getWinNumbers());
setWinBalls([]);
setBonus(null);
setRedo(false);
timeouts.current = [];
}, [winNumbers]);
return (
<>
<div>당첨 숫자</div>
<div id="결과창">
{winBalls.map(v => (
<Ball key={v} number={v} />
))}
</div>
<div>보너스!</div>
{bonus && <Ball number={bonus} />}
{redo && <button onClick={onClickRedo}>한 번 더!</button>}
</>
);
}
以上是关于javascript React Hooks useMemo useCallback的主要内容,如果未能解决你的问题,请参考以下文章
javascript React Hooks setInterval
javascript React Hooks简单相同
如何转换从@apollo/react-hooks 接收到的数据
javascript React hooks에서이전결과값받아올때
JS周刊#423 - React v16.8 发布:Hooks,对 Vue 来说 Hooks 意味着什么,Vue 2.6 发布
javascript React hooks - useRef로변수사용하기(값은변경되지만화면에영향끼치지않음)