React挂钩无法推送到当前值为全0的数组,即[0,0,0]

时间:2019-11-15 20:22:51

标签: javascript reactjs react-hooks

我正在使用挂钩在特定上下文中将新值推送到数组。该值始终是一个数字,除非当前数组的值全为零,否则我的代码每次都起作用。请参阅下面的代码,位于useEffect ...中,我正在尝试在特定条件下将新值'0'推送到homeInningScores和awayInningScores。对于homeInningScores和awayInningScores都等于[0,0,0]的一个特定实例,这总是可以接受的,在这种情况下,它不会推送任何内容。

const initialState = {
  homeInningScores: [],
  awayInningScores: [],

  }
  
const [homeInningScores, setHomeInningScores] = useState(
    initialState.homeInningScores
  )
  
const [awayInningScores, setAwayInningScores] = useState(
    initialState.awayInningScores
  )
  
  
useEffect(() => {

    const isLeader = homeScore > awayScore || awayScore > homeScore

    if (currentInning > innings && homeScore && !isLeader) {
      
      setInnings(innings + 1)

      //This part correctly pushes to the array UNLESS homeInningScores or awayInningScores is [0,0,0]
      setHomeInningScores(homeInningScores => [...homeInningScores, 0])
      setAwayInningScores(awayInningScores => [...awayInningScores, 0])
    } 
    })

1 个答案:

答案 0 :(得分:0)

我认为问题出在这里:

if (currentInning > innings && homeScore && !isLeader) {

如果homeScore = 0,则在javascript中也将其评估为“ false”。您应该检查homeScore == null或未定义或类似的内容。一个数字的布尔值可以为0或1。