【问题标题】:Moment JS - isAfter returning .isAfter is not a function?Moment JS - isAfter 返回 .isAfter 不是函数吗?
【发布时间】:2019-03-14 12:07:30
【问题描述】:

我的 React 组件内部有问题。我试图只显示未来或今天即将到来的数据。但我得到这个错误:

.isAfter 不是函数当我使用格式时。

没有它的格式,但我得到错误的数据。

简而言之:我只想显示即将发生的事件。

我的代码:

showData = () => {
    const { checks } = this.props;

    return (
        this.state.opendagen.length > 0 &&
        this.state.opendagen.map((value, index) => {
            const { opendag_data: datum } = value;
            const date = Moment(datum, 'DD/MM/YYYY').format('DD/M/YYYY');
            const now = Moment().format('DD/M/YYYY');

            console.log('vandaag:', now, 'data:', date);

            const concatData = [
                ...(value.opendag_department + ' - '),
                ...(value.opendag_data + ' - '),
                ...value.opendag_link,
            ];

            return date.isAfter(now) ? (
                <tr key={index}>
                    <td data-th="Datum">{value.opendag_data}</td>
                    <td data-th="Opleiding">
                        <strong>{value.opendag_department}</strong>
                    </td>
                    <td data-th="Link">
                        <a
                            target="_blank"
                            rel="noopener noreferrer"
                            href={value.opendag_link}>
                            bekijk website
                        </a>
                    </td>
                    <td data-th="Select">
                        <CheckBox
                            thisClassName="data__checkbox checkbox__input"
                            value={concatData.join('')}
                            id={'string_' + index}
                            onChange={checks}
                        />
                    </td>
                </tr>
            ) : null;
        })
    );
};

【问题讨论】:

  • 当您调用format 时,您会将时刻转换为字符串。尝试删除.format('DD/M/YYYY'),看看是否可行。
  • 使用Moment(date, 'DD/M/YYYY').isAfter(now)将sting转换为moment对象。

标签: javascript reactjs momentjs


【解决方案1】:

date 变量不是moment 对象,因为您在这里使用了format

const date = Moment(datum, 'DD/MM/YYYY').format('DD/M/YYYY');

moment 对象的 format 方法返回一个格式化的字符串,所以你的 date 变量只是一个字符串。

【讨论】:

    【解决方案2】:

    Moment().format() 将返回一个字符串。字符串不会响应isAfter()

    您需要将格式化的日期分配给另一个变量,或者只是在您希望显示的位置对其进行格式化:

    const date = Moment(datum, 'DD/MM/YYYY');
    const now = Moment();
    
    return date.isAfter(now) ? ( // <-- this now works 
      ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-17
      • 2012-12-03
      • 1970-01-01
      相关资源
      最近更新 更多