reactjs 条件渲染的问题

yxyvkwin  于 2022-12-22  发布在  React
关注(0)|答案(2)|浏览(112)

我正在尝试标记在我的网站上被点击的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([])

llycmphe

llycmphe1#

正如我所说:

  • 不要使用内联单击处理程序。它会使标记难以阅读。
  • findIndex!== -1不是必需的,因为您已经在检查它是否包含在数组中
  • 还有gameChoices.includes('Fortnite')=== false是多余的。只要一个简单的else就足够了

但除此之外,您还需要将value设置为state。
除此之外,你应该检查.some并检查相同大小写的文本。如果游戏名称来自用户输入,你还可以进行修剪

const choiceExists = (game) => {
    return gameChoices.some(
    (name) => name.toLowerCase() === game.toLowerCase()
  )
}
const clickHandler = () => {
    const name = 'fortnite'
  if (choiceExists(name)) {
    const newGames = gameChoices.filter((game) => game.toLowerCase() !== name)
    setGameChoices(newGames)
  } else {
    setGameChoices((choices) => choices.concat(name))
  }
}

<Container onClick={clickHandler} 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>
e1xvtsh3

e1xvtsh32#

更新无功状态值时,应使用状态设置器方法,因此setGameChoices((choices)=>[...choices, 'Fortnite'])

相关问题