useState() 是异步的问题

Issue with useState() being asynchronous

我有一个状态对象:

const [offersList, setOffersList] = useState(currentOffers)

我更新然后使用它的值:

setOffersList([...offersList, newOfferProperties])

const updateProperties = {
  id: auctionId,
  key: 'offersLog',
  newValue: offersList
}

问题是在 updateProperties 中,分配给键 newValue 的状态值不是

最新的值(在此上下文中提供),但由于 useState()

的异步性质,倒数第二个

我该如何解决这个问题?

setState 是异步的。在 offersList 更新之前,您正在访问它。您可以将 newOfferProperties 传递给 offersList

const updateProperties = {
  id: auctionId,
  key: 'offersLog',
  newValue: [...offersList, newOfferProperties]
}

传递 updater function to setOffersList to use the latest value. You can also memoize updateProperties 以便在相关依赖项更改时更新。

setOffersList((prevList) => [...prevList, newOfferProperties]);

const updateProperties = React.useMemo(() => ({
  id: auctionId,
  key: 'offersLog',
  newValue: offersList
}), [auctionId, offersList]);

此问题是在尝试更新触发事件中的状态时出现的。 在这种情况下,您需要做的是先将状态的新值分配到一个变量中,然后使用该变量进行状态更新和updateProperties。

const newOfferList = [...offersList, newOfferProperties];

setOffersList(newOfferList);

const updateProperties = {
    id: auctionId,
    key: 'offersLog',
    newValue: newOfferList
};

你的问题有问题。您不能在 setState() 之后立即使用 setOffersList。 相反,您应该做的是在函数或 useEffect 挂钩操作中扭曲 setOffersList。然后你的组件将被重新渲染并且你的 updateProperties 获得最新的状态

const [offersList, setOffersList] = useState(currentOffers)

function updateOfferList() {
  setOffersList([...offersList, newOfferProperties])
}

// or update the offerList in a useEffect hook on some conditions 

const updateProperties = {
  id: auctionId,
  key: 'offersLog',
  newValue: offersList
}