【问题标题】:Having trouble importing a function from date-fns in one component but not another?在一个组件中从 date-fns 导入函数但在另一个组件中导入函数时遇到问题?
【发布时间】:2023-03-05 19:26:01
【问题描述】:

我正在尝试将此函数从date-fns 库中导入我的组件之一,如下所示:

import { eachMonthOfInterval } from "date-fns";

我正在组件中这样测试它:

  let result = eachMonthOfInterval({
      start: props.state.startDate ? new Date(props.state.startDate) : '', 
      end: props.state.endDate ? new Date(props.state.endDate) : ''
    })

  console.log(result)

不幸的是,我不断收到TypeError: Object(...) is not a function

奇怪的是,像这样导入时,我可以在另一个组件中使用来自 date-fnsformat()

import {format} from "date-fns";

所以...这是一个错误还是我在这里做错了什么?

编辑:这是文档https://date-fns.org/v2.14.0/docs/eachMonthOfInterval的链接

【问题讨论】:

    标签: reactjs typeerror date-fns


    【解决方案1】:

    你能试试这个吗? 首先,在你的终端输入这个(确保终端在项目文件夹中):
    npm install date-fns --save

        import React, { Component } from 'react'
    import { eachMonthOfInterval } from 'date-fns'
    
    class TimeInterval extends Component {
       constructor(props) {
          super(props)
    
       }
    
       render() {
          var result = eachMonthOfInterval({
             start: new Date(2014, 1, 6),
             end: new Date(2014, 7, 10)
           })
           console.log(result);
          return (
             <div>
                <h1 id='title'>Interval</h1>
                <table id='students'>
                   <tbody>
    
                   </tbody>
                </table>
             </div>
          )
       }
    }
    
    export default TimeInterval;
    

    【讨论】:

    • 早些时候尝试过...不幸的是,我收到了一个找不到模块的错误。
    • 你可以试试这个:var result = eachMonthOfInterval({ start: new Date(2014, 1, 6), end: new Date(2014, 7, 10) })
    • 已经这样做了;它绝对不是日期对象或格式。该功能没有导入到组件中,即使它是从正确的位置拉出的。几乎是我的环境和那个特定功能有问题......但我不确定。
    • 我认为还有更多内容...我尝试在有效的组件中使用该功能,但它仍然给了我一个 TypeError。可能是图书馆问题?
    • 是的,它仍然无法工作......这绝对是我的环境问题,我不知道它是什么。老实说,这很令人沮丧。
    猜你喜欢
    • 2022-08-06
    • 2019-03-01
    • 1970-01-01
    • 2020-05-19
    • 1970-01-01
    • 2018-05-02
    • 2021-05-10
    • 2017-10-22
    • 2021-09-09
    相关资源
    最近更新 更多