React条件渲染问题:点击更新数组后标记不显示
问题原因与解决方案
核心问题
你直接通过splice、push修改了gameChoices这个state数组,没有使用React提供的setGameChoices更新state。React依赖state的不可变更新来检测变化、触发组件重渲染,直接修改原数组不会触发重渲染,导致UI上的标记无法更新,同时后续的includes判断也会因为state没有正确更新出现异常。
另外,你代码里的else if判断完全多余,直接用else即可,因为includes只有true/false两种结果。
修复后的代码
点击事件逻辑重构
把直接修改数组的操作改成创建新数组,通过setGameChoices更新:
<Container onClick={() => { setGameChoices(prevChoices => { // 检查是否已存在Fortnite if (prevChoices.includes('Fortnite')) { // 用filter创建新数组,过滤掉Fortnite return prevChoices.filter(item => item !== 'Fortnite'); } else { // 用扩展运算符创建新数组,添加Fortnite return [...prevChoices, 'Fortnite']; } }); }} fluid className="d-flex fortnite gameoption position-relative" > {gameChoices.includes('Fortnite') ? <> <BsCheckSquare color="lightgreen" size="2rem" style={{ top: '50%', right: '50%' }} /> </> : null } <h1 className="fw-bolder text-light text-center m-auto">FORTNITE</h1> </Container>
修复逻辑说明
- 使用
setGameChoices的函数式更新(传入prevChoices),确保每次操作的都是最新的state值,避免异步更新导致的state不一致问题。 - 用
filter和扩展运算符创建新数组,遵循React state不可变的原则,让React能正确检测到state变化,触发组件重渲染,UI上的标记就能正常显示了。
补充说明
你截图里的gameChoices数组已经有Fortnite,但includes返回false,本质也是因为直接修改原数组后,React没有更新组件的state引用,组件仍然使用旧的state进行判断,所以出现了视觉上数组有值但判断为false的矛盾情况。
内容的提问来源于stack exchange,提问作者Daniel Olsen
相关产品推荐
相关产品推荐

