我试图通过将 fillCalendar()
从组件的方法中提取到它自己的 js 文件中并导入它来清理这个 react 组件。最初 this.state.datesArray 是在 componentWillMount() 生命周期方法中设置的。现在我试图在构造函数中直接初始化它,因为这就是 react 文档 recommends .现在这样做会抛出“TypeError: Object(...) is not a function”错误,我不知道为什么。这是 Calendar.js 使用的样子 see here .
日历.js
import React, { Component } from 'react';
import { fillCalendar } from '../calendar.tools'
class Calendar extends Component {
constructor(props) {
super(props)
this.state = {
datesArray: fillCalendar(7, 2018),
date: new Date(),
monthIsOffset: false,
monthOffset: new Date().getMonth(),
yearOffset: new Date().getFullYear()
}
}
render() {
return (
...
)
}
}
日历工具.js
let fillCalendar = (month, year) => {
let datesArray = []
let monthStart = new Date(year,month,1).getDay()
let yearType = false;
let filledNodes = 0;
// Check for leap year
(year%4 === 0) ?
(year%100 === 0) ?
(year%400) ? yearType = true : yearType = false :
yearType = true :
yearType = false
const monthArrays = yearType ? [31,29,31,30,31,30,31,31,30,31,30,31] : [31,28,31,30,31,30,31,31,30,31,30,31]
if (month === 0) { month = 12; }
let leadDayStart = monthArrays[month-1] - monthStart + 1
// Loop out lead date numbers
for (let i = 0; i < monthStart; i++) {
datesArray.push({date: leadDayStart, type: "leadDate", id: "leadDate" + i})
leadDayStart++
filledNodes++
}
if (month === 12) { month = 0; }
// Loop out month's date numbers
for (let i = 0; i < monthArrays[month]; i++) {
datesArray.push({date: i + 1, type: "monthDate", id: "monthDate" + i})
filledNodes++
}
// fill the empty remaining cells in the calendar
let remainingNodes = 42 - filledNodes;
for (let i = 0; i < remainingNodes; i++) {
datesArray.push({date: i + 1, type: "postDate", id: "postDate" + i})
}
return datesArray
}
最佳答案
看起来不错,您只需导出
您的函数即可。
使用
export let fillCalendar = (month, year) => {
代替
let fillCalendar = (month, year) => {
关于javascript - TypeError : Object(. ..) 不是函数 reactjs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51997481/