【发布时间】:2021-05-07 01:35:58
【问题描述】:
我正在尝试在发布之前进行我的第一个 React 构建并遇到这样的 React Hook 错误: “React Hook useEffect 缺少依赖项:'colors' 和 'options'。要么包含它们,要么删除依赖项数组。
我的组件在最后一行显示错误。我做错了什么?
function MemoryGame({ options, setOptions, highScore, setHighScore }) {
const [game, setGame] = useState([]);
const [flippedCount, setFlippedCount] = useState(0);
const [flippedIndexes, setFlippedIndexes] = useState([]);
const colors = [
`url(${Background1})`,
`url(${Background13})`,
`url(${Background3})`,
`url(${Background4})`,
`url(${Background5})`,
`url(${Background6})`,
`url(${Background7})`,
`url(${Background8})`,
`url(${Background9})`,
`url(${Background14})`,
`url(${Background11})`,
`url(${Background12})`,
];
useEffect(() => {
const newGame = [];
for (let i = 0; i < options / 2; i++) {
const firstOption = {
id: 2 * i,
colorId: i,
color: colors[i],
flipped: false,
};
const secondOption = {
id: 2 * i + 1,
colorId: i,
color: colors[i],
flipped: false,
};
newGame.push(firstOption);
newGame.push(secondOption);
}
const shuffledGame = newGame.sort(() => Math.random() - 0.5);
setGame(shuffledGame);
}, []);
我刚刚添加了[colors, options],但现在得到了这个:'colors' 数组使 useEffect Hook(在第 137 行)的依赖关系在每次渲染时都会发生变化。将它移到 useEffect 回调中。或者,将 'colors' 的初始化封装在它自己的 useMemo() Hook 中。
现在我尝试将 const colors 移动到 useEffect 并且变得不确定。我还做错了什么?
useEffect(() => {
const colors = [
`url(${Background1})`,
`url(${Background13})`,
`url(${Background3})`,
`url(${Background4})`,
`url(${Background5})`,
`url(${Background6})`,
`url(${Background7})`,
`url(${Background8})`,
`url(${Background9})`,
`url(${Background14})`,
`url(${Background11})`,
`url(${Background12})`,
];
const newGame = [];
for (let i = 0; i < options / 2; i++) {
const firstOption = {
id: 2 * i,
colorId: i,
color: colors[i],
flipped: false,
};
const secondOption = {
id: 2 * i + 1,
colorId: i,
color: colors[i],
flipped: false,
};
newGame.push(firstOption);
newGame.push(secondOption);
}
const shuffledGame = newGame.sort(() => Math.random() - 0.5);
setGame(shuffledGame);
}, [colors, options]);
【问题讨论】:
标签: reactjs