[英]How to execute a function right after state gets updated with Hooks in React Native?
作為我在 Javascript 和 React Native 的瑣碎經驗,我一直在努力解決如何在我的 state 更新日期之后立即調用checkValidDate
來執行 function。
我正在使用react-native-modal-date-time-picker來選擇日期。
這是我的代碼:
const [chosenStartDate, setChosenStartDate] = useState('');
const [chosenStartDate_unix, setChosenStartDate_unix] = useState(null);
const [chosenEndDate, setChosenEndDate] = useState('');
const [chosenEndDate_unix, setChosenEndDate_unix] = useState(null);
const handleConfirm = (day) => {
hideDatePicker(); // Set isDatePickerVisible to false
if(chosenMode){ // If true, calendar shows up for choosing starting date, false --> for choosing ending date
setChosenStartDate(moment(day).format('MMMM Do YYYY, h:mm:ss a'));
setChosenStartDate_unix(parseInt((new Date(moment(day).format()).getTime())/60000));
// Convert date to epoch time
}else{
setChosenEndDate(moment(day).format('MMMM Do YYYY, h:mm:ss a'));
setChosenEndDate_unix(parseInt((new Date(moment(day).format()).getTime())/60000));
checkValidDate(chosenStartDate_unix,chosenEndDate_unix)
// --> I know that the dates only get updated after the handleConfirm has been executed
// --> So basically, the chosenEndDate_unix passed in checkValidDate at this moment is still
// null. Therefore, I can't check it correctly
}
};
const checkValidDate = (start, end) => {
console.log('Checking')
console.log('chosenEndDate_unix', chosenEndDate_unix);
console.log('chosenStartDate_unix', chosenStartDate_unix);
if(start && end){
((end - start) >= 5)
? (console.log('VALID'))
: (alert('Please travel aleast 5 minutes, life is worth explored!'), setChosenEndDate(''))
}
}
//...
return(
//...
{isDatePickerVisible && (
<DateTimePickerModal
isVisible={isDatePickerVisible}
mode={mode}
onConfirm={(day) => {
handleConfirm(day)
// I tried to execute the checkValidDate here, but it also doesn't work
}}
onCancel={hideDatePicker}
/>
)}
)
基本上,我有 2 個按鈕。
一個用於選擇不需要檢查的startDate
。
另一個用於選擇需要檢查startDate
是否超過至少 5 分鍾的endDate
當按下startDate
按鈕時, chosenMode
將被設置為true
,反之亦然endDate
按鈕
handleConfirm
是 function 我們將在我們按下日歷上的OK
按鈕時執行。 按照react-native-modal-date-time-picker
picker 的設計,只有當我們按下OK
時,選擇的日期才會傳遞給onConfirm
我們如何在chosenEndDate
和chosenEndDate_unix
更新后立即執行checkValidDate
?
請幫我
您可以使用useEffect
。 當 selectedEndDate 或 selectedEndDate_unix 更改時,將調用 checkValiddate。
useEffect(()=>{
checkValiddate()
}, [chosenEndDate, chosenEndDate_unix]);
官方文檔有更多關於它是如何工作的信息: https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects
非常感謝李宇鵬。 感謝您的建議,我想出了解決方案
順便說一句,當我們放置 2 個依賴項時,它們會同時發生變化。 checkValidDate() 將被執行兩次。 所以我們將只放置 1 個依賴項,即chosenEndDate_unix
useEffect(() => {
if(!chosenMode) checkValidDate(chosenStartDate_unix, chosenEndDate_unix)
}, [chosenEndDate_unix])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.