修改解构的反应状态将更新组件的状态

时间:2020-08-27 06:03:33

标签: javascript reactjs react-redux

我具有以下用于保存约会的功能:

handleAppointmentSave = event => {
    event.preventDefault()
    const { appointment } = this.state

    const appointmentErrors = apppointmentFormIsValid(appointment)
    this.setState({ appointmentErrors })
    if (!(Object.keys(appointmentErrors).length === 0)) return
    const localeDate = appointment.transactionDate.toLocaleString()
    appointment.transactionDate = moment
      .tz(localeDate, 'DD.MM.YYYY, HH:mm', 'UTC')
      .format('YYYY-MM-DD HH:mm:ss')

    const { saveAppointment, history } = this.props
    
    saveAppointment(appointment)
      .then(appointmentId => {
        debugger;
      })
      .catch(error => {
      })
  }

我的问题是结构化语句const { appointment } = this.state。当我修改已分解的约会transactionDate时,this.state.appointment.transactionDate也被更改了。尽管这并不会立即触发重新渲染,并且由于点击state操作而导致redux saveAppointment更新时一切都很好,但是将触发重新渲染并且格式错误的transactionDate会中断日期选择器组件。

到目前为止,我发现的唯一解决方案是在保存ID并对其进行处理之前,对州的任命进行深入复制:

const appointment = JSON.parse(JSON.stringify(this.state.appointment));
appointment.transactionDate = this.state.appointment.transactionDate;

这是唯一的解决方案和正常行为吗?

0 个答案:

没有答案