gpt4 book ai didi

reactjs - 显示重复图像 - useEffect 问题?

转载 作者:行者123 更新时间:2023-12-04 07:57:28 24 4
gpt4 key购买 nike

我有一些代码来显示我的板,如下所示:

 <Grid item xs={6} justify="center">
<Paper id="board">
</Paper>
</Grid>
但有时当我保存我的代码时,它会在 localhost:3000 的屏幕上显示一个重复的板,尽管并非总是如此。下面的例子:
Double image issue
我怀疑它可能与我的 useEffect 有关:
 useEffect(() => {
// componentDidMount() {
const board = new Gameboard(document.getElementById('board'), {
// position: 'r4r1k/p1P1qppp/1p6/8/5B2/2Q1P3/P4PPP/R3KB1R b KQ - 0 21',
position: game.fen(),
sprite: {
url: './gameboard-sprite.svg', // pieces and markers are stored as svg in the sprite
grid: 40, // the sprite is tiled with one piece every 40px
cache: true,
},
orientation: COLOR.white,
moveInputMode: MOVE_INPUT_MODE.dragPiece,
responsive: true,
});
board.enableMoveInput(inputHandler);
}, []);
知道为什么它可以显示两次,但只是有时吗?如果有帮助,当我单击浏览器刷新按钮时,它总是会删除重复的板。但是当我第一次保存我的代码时,它经常出现。

最佳答案

将您的 Gameboard 实例保存在 useRef 中,这样只会创建一个实例:

const board = useRef(); 

useEffect(() => {
if(!board.current) {
board.current = new Gameboard(document.getElementById('board'), {
// position: 'r4r1k/p1P1qppp/1p6/8/5B2/2Q1P3/P4PPP/R3KB1R b KQ - 0 21',
position: game.fen(),
sprite: {
url: './gameboard-sprite.svg', // pieces and markers are stored as svg in the sprite
grid: 40, // the sprite is tiled with one piece every 40px
cache: true,
},
orientation: COLOR.white,
moveInputMode: MOVE_INPUT_MODE.dragPiece,
responsive: true,
});
board.current.enableMoveInput(inputHandler);
}
}, []);

关于reactjs - 显示重复图像 - useEffect 问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66627334/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com