首页 > 解决方案 > TypeError:无法读取未定义的属性“formatAMPM”

问题描述

我正在导入一个要测试的模块(称为 activity.js)。此模块(activity.js)使用以下方式导入 formatAMPM: import {formatAMPM} from '../config/helper-> activity.js

我从 react-native 0.55.4 更新到 0.58.6 using https://react-native-community.github.io/upgrade-helper/?from=0.55.4&to=0.58.6,也许这导致了问题。但我不确定。

活动.js

import {
    SET_ACTIVITY_DATE,
    SET_ACTIVITY_START_TIME,
    SET_ACTIVITY_DURATION,
    SET_ACTIVITY_SRC,
    SET_ACTIVITY_DEST,
    SET_ACTIVITY_TYPE,
    SET_ACTIVITY_DISTANCE,
    SET_ACTIVITY_CO2
} from '../actions/ActivityDetailsAction';
import { formatAMPM } from '../config/helper';

export default function activity(
    state = {
        date: new Date().toDateString(),
        startTime: formatAMPM(new Date()),
        duration: 0,
        src: { latitude: -1, longitude: -1 },
        dest: { latitude: -1, longitude: -1 },
        type: 'STILL',
        distance: 0,
        co2: 0
    },
    action
) {
    switch (action.type) {
        case SET_ACTIVITY_DATE:
            return Object.assign({}, state, {
                date: action.value
            });
            ...

助手.js

/**
 * helper function to format date
 * @param  Date date
 * @return {time} formatted time
 */
export function formatAMPM(date) {
    var hours = date.getHours();
    var minutes = date.getMinutes();
    var ampm = hours >= 12 ? 'pm' : 'am';
    hours = hours % 12;
    hours = hours ? hours : 12; // the hour '0' should be '12'
    hours = hours < 10 ? '0' + hours : hours;
    minutes = minutes < 10 ? '0' + minutes : minutes;
    var time = hours + ':' + minutes + ' ' + ampm;
    return time;
}

当我运行时npm run test,此错误消息显示在终端中:

TypeError: Cannot read property 'formatAMPM' of undefined

      33 |     },
      34 |     action
    > 35 | ) {
      36 |     switch (action.type) {
      37 |         case SET_ACTIVITY_DATE:
      38 |             return Object.assign({}, state, {

标签: reactjsreact-nativejestjsbabeljs

解决方案


推荐阅读