【问题标题】:Format moment in React State immmutablyReact State 中的格式化时刻一成不变
【发布时间】:2018-05-16 14:23:21
【问题描述】:

我正在尝试将状态中的时刻对象格式化为字符串,然后以不可变的方式发送到数据库,以免改变状态。

        this.state = {
            startDate: moment()
        }

状态需要是 React DatePicker 的对象。 所以在提交我的表单时,我想将 startDate 更改为字符串。

        handleSubmit(event) {
            event.preventDefault();

             const newState = { 
                ...this.state,  
                startDate : { ...this.state.startDate } 
             };

             newState.startDate.format('YYYY-MM-DD');


             this.RegisterEmployeeService.registerEmployee(newState)
             .then((res) => {
                Swal('Registered!');
             })  
        }

但在 newState.startDate 对象上运行“.format()”时出现错误。

          <DatePicker
                selected={this.state.startDate}
                onChange={this.handleStartDateChange.bind(this)}/>

错误:

      TypeError: newState.startDate.format is not a function

【问题讨论】:

  • 错误是什么?
  • 道歉,我把它放在上面了

标签: reactjs ecmascript-6 redux datepicker momentjs


【解决方案1】:

我相信这与startDate : { ...this.state.startDate }有关

将其更改为:startDate : this.state.startDate,它应该可以工作!

应该是这样的:

const newState = { 
    ...this.state,  
    startDate: this.state.startDate
};

【讨论】:

  • 问题在于 startDate 是一个对象。所以我相信我需要使用传播运算符来深度克隆状态?
  • 在这种情况下你能做的最好的就是使用Object.assign({}, yourObj);它会深度克隆对象
【解决方案2】:

正如 Saurabh Sharma 所说,{...this.state.startDate} 会引起问题。

要将格式化的日期放入您的 newState 变量中,我建议您像这样编写 handleSubmit 函数:

handleSubmit = event => {
    event.preventDefault()

    const formattedDate = this.state.startDate.format('YYYY-MM-DD'),
      newState = {
        ...this.state,
        startDate: formattedDate
      }

     this.RegisterEmployeeService.registerEmployee(newState)
     .then((res) => Swal('Registered!'))
}

如果您不想要另一个变量,也可以只内联 formattedDate:

const newState = {
    ...this.state,
    startDate: this.state.startDate.format('YYYY-MM-DD')
}

- 编辑-

如果您担心无意中修改现有状态(使用 Momentjs 很容易做到),您可以使用 ES6 assign method 克隆现有状态:

const newState = Object.assign({}, ...this.state);

上面所做的是获取一个空对象并将您的状态克隆到其中。通过这样做,您可以随意修改newState,而无需触及原始this.state

newState.startDate = newState.startDate.format('YYYY-MM-DD')

【讨论】:

  • 在这个实现中我不会深度克隆状态? startDate 是一个对象,所以这就是我在状态和 startDate 上使用扩展运算符的原因。 format() 是改变状态还是从状态中创建一个新变量?
  • @Fraser 我在上面做了一个编辑,为了保护你的状态不被修改,我可以使用 Object.assign 方法克隆它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-22
  • 2017-11-17
  • 2020-01-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多