状态钩子不会从 useEffect 函数调用中更新

时间:2021-01-13 00:46:46

标签: reactjs react-hooks use-effect use-state

在 useEffect 中,我调用 getPins 来查询数据库中的引脚。然后我循环遍历引脚并尝试减少作为状态钩子的“pinsRemaining”。

在 state 中它显示钩子减少了,但它在代码中不起作用。当我从 getPinnedLocations() 控制台日志 pinRemaining 时,它总是相同的数字。

有趣的是,如果我将 'pinsRemaining' 设为 const 变量(不是状态挂钩),它确实可以减少计数器,但这会产生其他问题。

我不知道如何让这段代码工作。我在这里阅读了状态钩子是如何异步的

useState set method not reflecting change immediately

我试过像这样添加一个空的 useEffect 钩子,但它不起作用

 useEffect(() => {}, [pinsRemaining])

也许我需要在这里面做点什么?

这是我的完整代码。

const [pinsRemaining, setPinsRemaining] = useState(5)


  useEffect(() => {

    if (isLoggedIn && user !== {}) {

      APIService.getAccountById(
        Number(id)
      ).then(_user => {
        setUser(_user)
        getPins(_user)
      }).catch(err => {
        console.log("error", err)
      })

    } 

  }, []);

  const getPins = (_user) => {
    APIService.getPinsForUser(_user.id).then(pins => {

      pins.map(pin => {


        pushPinnedLocation(pin.location_id, _user)
      })
    })
    
  }

   const pushPinnedLocation = (location, date, _user) => {

//decrementing in hook doesn't work here
  setPinsRemaining((prevState)=> prevState - 1)

//but decrementing with var does
    pins = pins - 1

    console.log("state hook", pinsRemaining)
    console.log("const var", pins)


    setLocationDateMap(new Map(locationDateMap.set(location, date)))

if(pinsRemaining === 0){
    getMatchesFromDB(_user)
}
  
  }


const getMatchesFromDB = (_user) => {
 
    let pinsArray = Array.from(locationDateMap)
    pinsArray.map(obj => {
      let location = obj[0]
      let date = obj[1]
      let locationDate = date + "-" + location
   
      let dbMatches;

      let params = {
        location_date_id: locationDate, 
        user_id: _user.id, 
        seeking: _user.seeking
      }
      APIService.getMatchesByLocationDateId(params).then(data => {

       dbMatches = data.map((match, i) => {
        

        if(match.likes_recieved && match.likes_sent 
          && match.likes_recieved.includes(_user.id + "")
          && match.likes_sent.includes(_user.id + "")){

          match.connectedStatus = 3
          
        }else if(match.likes_recieved && match.likes_recieved.includes(_user.id + "")){
          match.connectedStatus = 2
        }else if(match.likes_sent && match.likes_sent.includes(_user.id + "")){
          match.connectedStatus = 1
        }else{
          match.connectedStatus = 0
        }

        match.name = match.user_name
         return match
       })


      }).then(() => {

        setMatches(matches => [...matches, ...dbMatches]);
      })

    })
  
}

0 个答案:

没有答案