React Redux翻牌配对游戏事件处理函数交替执行异常修复求助
React翻牌配对游戏bug修复方案
核心问题清单及修复方法
1. resetUnmatchedCards调用未执行action creator
Card组件里的resetHandler派发action时,没有调用resetUnmatchedCards()生成action对象,而是直接把函数本身传给了dispatch,导致重置逻辑完全不生效。
修复代码:
// Card.js 中的resetHandler修改为 const resetHandler = () => { dispatch(resetUnmatchedCards()) }
2. 卡牌样式逻辑完全错误
当前逻辑只要卡牌未匹配就会设为no-match,导致正常翻开未配对的卡牌也显示红色,且默认的resting样式永远不会生效,未翻开的卡牌也会被错误绑定样式。
修复代码:
// Card.js 中的样式逻辑整体替换为 let cardStyle = 'resting'; let click = () => flipHandler(id); let cardText = ( <img src={cardLogo} className="logo-placeholder" alt="Card option" /> ); if (visibleIDs.includes(id) || matchedIDs.includes(id)) { cardText = contents; click = () => {}; if (matchedIDs.includes(id)) { cardStyle = 'matched'; } else if (visibleIDs.length === 2) { cardStyle = 'no-match'; } } if (visibleIDs.length === 2) { if (cardStyle === 'no-match' ) { click = () => resetHandler(); } // 移除原逻辑中覆盖click的冗余代码 }
3. 两张卡牌不匹配时无延迟直接翻回
用户看不到第二张卡牌的内容就会被翻回,体验极差,需要增加延迟自动执行重置逻辑。
修复代码:
// Card.js 组件内增加useEffect逻辑 useEffect(() => { if (visibleIDs.length === 2) { const timer = setTimeout(() => { dispatch(resetUnmatchedCards()) }, 1000) return () => clearTimeout(timer) } }, [visibleIDs, dispatch])
4. 匹配成功后卡牌visible状态设置不符合逻辑
flipCard reducer中,匹配成功的卡牌被设置为visible: false,虽然不会影响显示(匹配状态会优先判断),但状态逻辑不符合预期,可按需修改。
修复代码:
// boardSlice.js flipCard分支的匹配逻辑修改为 if (card1.contents === card2.contents) { flipState[index1] = {...card1, visible: true, matched: true}; flipState[index2] = {...card2, visible: true, matched: true}; }
内容的提问来源于stack exchange,提问作者Borhen Kalboussi
相关产品推荐
相关产品推荐

