当与DateTimePicker克隆并使用时,Moment对象不会按天递增

问题描述

我有以下代码

const categories = [{
    "id": 2,"name": "Shirt","product": [{
        "id": 1,"product_name": "Shirt 123","price": "150.00","image": "http://localhost/l9FRGvZDfb.jpeg"
    },{
        "id": 4,"product_name": "Shirt 456","price": "12.44","image": "http://localhost/A5rmGtOnW9.jpeg"
    }]
},{
    "id": 3,"name": "Froots","product_name": "Apple 121","image": "http://localhost/Dfb.jpeg"
    },"product_name": "Banana 121","image": "http://localhost/tOnW9.jpeg"
    }]
}]

const input = 'Shir'

// Obtain a flattened array of all products
// Include the id of the category it came from as well
const products = []
categories.forEach(category => {
  category.product.forEach(product => {
    products.push({
       category: category.id,...product
    })
  })
})

// Filter the list of products by name that starts with the input
// Note that you can replace the `product.product_name.startsWith(input)` with any filter function to improve your search
// Then return the category that that product came from
// Finally remove any duplicates using [...new Set()]
const selectedCategories = [...new Set(
  products
    .filter(product => product.product_name.startsWith(input))
    .map(product => product.category)
)]

// Return the categories we found by searching through our initial list of categories
const output = categories.filter(category => selectedCategories.includes(category.id))

console.log(output)

我正在使用以下React组件更改日期:

  function localDateHandler(momentObj) {


      let start = momentObj.clone();
      let update = start.add(10,'days');

      console.log(update);    // Does not change,SHOULD be ten days more than momentObj
      console.log(momentObj);

}

该组件的信息在这里https://material-ui-pickers.dev/

当我更改日期时,日期不会增加第一段代码中列出的天数(我会在注释中详细说明)

谢谢!

解决方法

我正在复制,这没有任何问题。您所看到的可能是由以下情况之一引起的:

  • 您可能已经简要查看了时刻对象的_i,这可能是初始对象(可能源自momentObj.clone()),相反,您应该查看_d({{ 3}})

    最常查看的内部属性是_d属性,其中包含Moment包装的JavaScript日期。

  • 您可能没有为矩适配器(moment object internal properties doc)使用正确版本的对等依赖项

    重要:对于材料用户界面选择器v3,请使用@ date-io适配器的 v1.x 版本。

用于演示的Codesandbox,您应该打开日志进行检查

installation guide

Edit frosty-mcnulty-wu5s1

,

JS代码可以正常工作(注释显然是错误的):

function localDateHandler(momentObj) {

      let start = momentObj.clone();
      let update = start.add(10,'days');

      console.log(update);    // Does not change,SHOULD be ten days more than momentObj
      console.log(momentObj);

}

localDateHandler(moment());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>

我的情况是:

"2020-08-24T22:29:35.347Z"
"2020-08-14T22:29:35.347Z"

我猜渲染有问题吗?然后,我怀疑您必须在eventDate中的某个地方修改localDateHandler,而不是一些未绑定到小部件的局部变量。