首页 > 解决方案 > 在函数上使用我的拆分日期数据有问题吗?

问题描述

我有一个日期选择器,它会给我一个选定的日期,我需要将此日期拆分为月、日和年,以便我可以查阅另一个用户数据,我可以正确拆分它并且 console.log 显示正确的日、月和年,问题是我不知道如何在函数中使用它们。当我在函数上使用它们时,它会抛出 undefined 。

这是我的代码

import DatePicker from 'react-native-datepicker';
const PersonalForm = ({onSubmit, errorMessage}) => {
    const [vBirthDate, setvBirthDate] = useState('');
    const [month, day, year] = vBirthDate.split('/')
    console.log(`Month: ${month}`)
    console.log(`Day: ${day}`)
    console.log(`Year: ${year}`)

    const RFC = () => {
        console.log(vName, 
        vSecondName, 
        vLastName, 
        vSecondLastName, 
        vBirthDate,
        vBirthDate.day,
         month,
        `Month: ${month}`, 
        `Day: ${day}`, 
        `Year: ${year}`);
        }
             return ( 
        <ScrollView>

        <View style={styles.containerdate}>
                <DatePicker 
                  date={vBirthDate} //initial date from state
                  mode="date" //The enum of date, datetime and time
                  placeholder="select date"
                  format="DD/MM/YYYY"
                  minDate="01/01/1900"
                  maxDate="01/01/2019"
                  confirmBtnText="Confirm"
                  cancelBtnText="Cancel"
                  androidMode="spinner"
                  customStyles={{
                    placeholderText: {
                      fontSize: 16,
                    },
                    dateIcon: {
                      height: 0,
                      width: 0,
                    },
                    dateText: {
                      color: '#b3b4b5',
                      fontSize: 16,
                    },
                    dateInput: {
                      borderWidth: 0,
                    }
                  }}
                  onDateChange={(date) => {setvBirthDate(date);RFC();} }
                />
              </View>
        </ScrollView>
    );
};

函数 RFC 打印除日期外的所有内容

标签: javascriptreactjsreact-native

解决方案


1)在更改事件中,将“日期”作为参数传递给 RFC 方法。

onDateChange={ (date) => { setvBirthDate(date); RFC(date); } }

2) 使用参数更新 RFC 方法

const [splitDate, setSplitDate] = useState({});
const RFC = (date) => {
    const [month, day, year] = vBirthDate.split('/');
    // Now, if needed you can save to state
    setSplitDate({ month, day, year });
    console.log(`Month: ${month}`, `Day: ${day}`, `Year: ${year}`);
}

推荐阅读