[英]How to ensure state is not stale in React hook
我在下面創建的按鈕似乎滯后於selectedButtonIdx
值。
調用getClass
, toggleSelected
是否未完成?
function ButtonGroup(props) {
const [selectedButtonIdx,setIdx]=useState(props.loadCurrentAsIndex);
const toggleSelected = (e) => {
setIdx(parseInt(e.target.dataset.index));
props.onclick(e);
};
const getClass = (index) => {
return (selectedButtonIdx === index) ? classnames('current', props.btnClass)
: classnames(props.btnClass)
};
let buttons = props.buttons.map((b, idx) => <Button key={idx} value={b.value} index={idx} text={b.text}
onclick={e => toggleSelected(e)}
btnClass={getClass(idx)}/>);
return (
<div>
{buttons}
</div>
);
}
每次點擊都希望通過更改其類來向用戶顯示組中的哪個按鈕被點擊。
通過看這個,
<Button
key={idx}
value={b.value}
index={idx}
text={b.text}
onclick={e => toggleSelected(e)}
btnClass={getClass(idx)}
/>
Button
是您的自定義組件,
這里要注意兩點,
onclick
( c
很小)道具,在您的實際組件中它應該是onClick={props.onclick}
e.target.dataset.index
,要處理dataset
我們應該具有帶有data-
前綴的屬性。 所以你的index
應該是你實際組件中的data-index
。 所以最后你的Button
組件應該是,
const Button = (props) => {
return <button text={props.text} data-index={props.index} onClick={props.onclick} className={props.btnClass}>{props.value}</button>
}
從 useState 返回的函數 setIdx 是異步的,這意味着它可能在您運行下一個函數時尚未完成(如您所料)。
看看useEffect它允許你指定一個函數,一旦你狀態中的一個項目發生變化,這個方法將確保你的函數以正確的順序被調用。
到現在為止,我沒有發現這里有任何問題。
這個怎么運作:
onClick
事件偵聽器已綁定setIdx
觸發新渲染selectedButtonIdx
用於渲染(以及getClass
調用) 看,沒有理由擔心setIdx
是同步函數還是異步函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.