javascript - 如何在使用 React Native 中的 Hooks 更新状态后立即执行函数?
问题描述
作为我在 Javascript 和 React Native 方面的琐碎经验,我一直在努力解决如何checkValidDate
在我的日期状态更新后立即执行函数调用。
我正在使用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
不需要检查的。另一个用于选择
endDate
需要检查是否更长的时间startDate
至少5分钟按下
startDate
按钮时,chosenMode
将设置为按钮,true
反之亦然endDate
handleConfirm
是我们按下OK
日历上的按钮时将执行的功能。按照设计react-native-modal-date-time-picker
,只有当我们按下OK
时,选择的日期才会传递给onConfirm
道具。
更新后我们如何才能执行checkValidDate
正确的操作?chosenEndDate
chosenEndDate_unix
请帮我
解决方案
您可以使用useEffect
. 当 selectedEndDate 或 selectedEndDate_unix 更改时,将调用 checkValiddate。
useEffect(()=>{
checkValiddate()
}, [chosenEndDate, chosenEndDate_unix]);
官方文档有更多关于它是如何工作的信息:https ://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects
推荐阅读
- javascript - 数据表在页面加载和刷新时简要显示已删除的行
- php - 是否可以将对象变量传递给匿名函数中的“使用”部分
- python - 从 Django 表单调用 Django-Rest API
- java - 升级到 2.x 时 org.refcodes.console.ConsoleSugar 缺少 switsh 和 helpSwitch 方法
- nginx - AWS EC2 上的 Flask-SocketIO 502 错误,带有 [CRITICAL] 工作线程超时
- ag-grid - 当 autoGroupColumnDef 更改时,AgGridReact 组件不更新
- python - 如何使用字典语法调用函数?
- cython - Texgenpack Wrapper - 编译问题
- css - 如何正确匹配我的子元素与其父元素的边界半径
- php - 隐藏具有相同“角色”的用户的数据