我正在尝试标记在我的网站上被点击的div。当我点击时,数组被更新,但标记不显示。看起来gameChoices.includes('Fortnite')
语句是假的,即使数组包含确切的值Fortnite
。
有人知道为什么会发生这种情况吗?最终会有一个新的解决问题的方法吗?
代码:
<Container onClick={() => {
if (gameChoices.includes('Fortnite')) {
const findIndex = gameChoices.findIndex(a => a === 'Fortnite')
findIndex !== -1 && gameChoices.splice(findIndex , 1)
} else if (gameChoices.includes('Fortnite') === false) {
gameChoices.push('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>
const [gameChoices, setGameChoices] = useState([])
2条答案
按热度按时间llycmphe1#
正如我所说:
但除此之外,您还需要将value设置为state。
除此之外,你应该检查
.some
并检查相同大小写的文本。如果游戏名称来自用户输入,你还可以进行修剪e1xvtsh32#
更新无功状态值时,应使用状态设置器方法,因此
setGameChoices((choices)=>[...choices, 'Fortnite'])