首页 > 解决方案 > 如何在使用 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 个按钮。

更新后我们如何才能执行checkValidDate正确的操作?chosenEndDatechosenEndDate_unix

请帮我

标签: javascriptreactjsreact-native

解决方案


您可以使用useEffect. 当 selectedEndDate 或 selectedEndDate_unix 更改时,将调用 checkValiddate。

useEffect(()=>{
    checkValiddate()
}, [chosenEndDate, chosenEndDate_unix]); 

官方文档有更多关于它是如何工作的信息:https ://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects


推荐阅读