无法提交回应表格

时间:2018-12-05 08:37:43

标签: reactjs redux

我有一种提交已编辑表格的方法,但是当我单击“提交”按钮时,什么也没有发生。通过控制台,我知道了eventIndex = -1。我应该在下面的代码中解决什么?

   editEvent(event) {
            const { currentUser, editGoogleCalendarEvent, calendarEvents } = this.props;
            const {

 events } = this.state;
        let onlyDate = false;

        console.log('event', event);
        console.log('calendarEvents', calendarEvents);
        const idx = events.indexOf(event);
        const eventIndex = _.findIndex(calendarEvents.details.items, { id: event.id });
        const editedEvent = { ...event };
        console.log('Event Index', eventIndex);
        const nextEvents = [...events];
        nextEvents.splice(idx, 1, editedEvent);
        if (eventIndex !== -1) {
          const item = calendarEvents.details.items[eventIndex];
          if (item.start.date && item.end.date) {
            editedEvent.start = moment(event.start).format('YYYY-MM-DD');
            editedEvent.end = moment(event.end).format('YYYY-MM-DD');
            onlyDate = true;
          }
        }

        this.setState({
          events: nextEvents,
        }, () => {
          console.log('Object', { id: event.event.id, title: event.formValues.title, userId: currentUser.id, timezone: currentUser.timezone, onlyDate });
          editGoogleCalendarEvent({
            id: event.event.id,
            start: moment(event.event.start).hours(event.formValues.period === 'AM' ? event.formValues.hour % 12 : (event.formValues.hour % 12) + 12).minutes(event.formValues.minute).toISOString(),
            end: moment(event.event.end).hours(event.formValues.period === 'AM' ? event.formValues.hour % 12 : (event.formValues.hour % 12) + 12).minutes(event.formValues.minute).toISOString(),
            title: event.formValues.title,
            userId: currentUser.id,
            timezone: currentUser.timezone,
            onlyDate,
          });
        });
      }

表格:

<EditCalendarEventForm
              show={this.state.editShow}
              isSubmitting={editEventProcess.isSubmitting}
              calendarEvent={this.state.calendarEvent}
              onSubmit={this.editEvent}
              onHide={this.hideEditEventModal}
            />

这里是整页,也许您会对此有所了解。我也有一个EditFormPage和api来处理请求。 我以moveEvent为例创建editEvent方法。

import React, { PropTypes } from 'react';
import moment from 'moment-timezone';
import Helmet from 'react-helmet';
import _ from 'lodash';
import { connect } from 'react-redux';
import { createStructuredSelector } from 'reselect';
import { GoogleLogin, GoogleLogout } from 'react-google-login';
import { reduxForm, reset } from 'redux-form';

import BigCalendar from 'react-big-calendar';
import withDragAndDrop from 'react-big-calendar/lib/addons/dragAndDrop';

import 'react-big-calendar/lib/less/styles.less';
import 'react-big-calendar/lib/addons/dragAndDrop/styles.less';

import AddCalendarEventForm from '../../../app/components/AddCalendarEventForm';

import EditCalendarEventForm from '../../../app/components/EditCalendarEventForm';

import { translate } from '../../../common/utilities/localization';

import {
  selectCurrentUser,
  selectCurrentGoogleUser,
} from '../../containers/App/selectors';

import {
  submitGoogleAuth,
  fetchGoogleCalendarEvents,
  editGoogleCalendarEvent,
  addGoogleCalendarEvent,
} from './actions';

import {
  selectGoogleAuth,
  selectCalendarEvents,
  selectAddEventProcess,
  selectEditEventProcess,
} from './selectors';

const formName = 'addCalendarEvent';

const formNameEdit = 'editCalendarEvent';

const DragAndDropCalendar = withDragAndDrop(BigCalendar);
const localizer = BigCalendar.momentLocalizer(moment);

const mapStateToProps = createStructuredSelector({
  currentUser: selectCurrentUser(),
  currentGoogleUser: selectCurrentGoogleUser(),
  googleAuth: selectGoogleAuth(),
  calendarEvents: selectCalendarEvents(),
  addEventProcess: selectAddEventProcess(),
  editEventProcess: selectEditEventProcess(),
});

const mapDispatchToProps = (dispatch) => ({
  submitGoogleAuth: (externalUserId, googleToken) => dispatch(submitGoogleAuth(externalUserId, googleToken)),
  fetchGoogleCalendarEvents: (data) => dispatch(fetchGoogleCalendarEvents(data)),
  editGoogleCalendarEvent: (data) => dispatch(editGoogleCalendarEvent(data)),
  addGoogleCalendarEvent: (data) => dispatch(addGoogleCalendarEvent(data)),
  resetForm: () => dispatch(reset(formName)),
  resetEditForm: () => dispatch(reset(formNameEdit)),
});

@reduxForm({
  form: formName,
})
@connect(mapStateToProps, mapDispatchToProps)
export default class CalendarPage extends React.Component {
  static propTypes = {
    currentUser: PropTypes.any,
    currentGoogleUser: PropTypes.any,
    submitGoogleAuth: PropTypes.func.isRequired,
    googleAuth: PropTypes.object,
    fetchGoogleCalendarEvents: PropTypes.func,
    calendarEvents: PropTypes.object,
    editGoogleCalendarEvent: PropTypes.func,
    addGoogleCalendarEvent: PropTypes.func,
    addEventProcess: PropTypes.object,
    editEventProcess: PropTypes.object,
    resetForm: PropTypes.func,
    resetEditForm: PropTypes.func,
  };

  constructor(props) {
    super(props);

    this.state = {
      events: [],
      show: null,
      calendarEvent: null,
      editShow: null,
    };

    this.onSuccess = this.onSuccess.bind(this);
    this.onFailure = this.onFailure.bind(this);
    this.moveEvent = this.moveEvent.bind(this);
    this.editEvent = this.editEvent.bind(this);
    this.newEvent = this.newEvent.bind(this);
    this.showEventModal = this.showEventModal.bind(this);
    this.showEditEventModal = this.showEditEventModal.bind(this);
    this.hideEventModal = this.hideEventModal.bind(this);
    this.hideEditEventModal = this.hideEditEventModal.bind(this);
  }

  componentDidMount() {
    const { currentUser, currentGoogleUser } = this.props;

    if (currentGoogleUser && currentGoogleUser.expires_at && moment(currentGoogleUser.expires_at).isAfter(moment())) {
      this.props.fetchGoogleCalendarEvents({ ...currentGoogleUser, userId: currentUser.id });
    }
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.currentGoogleUser !== this.props.currentGoogleUser) {
      this.props.fetchGoogleCalendarEvents({ ...nextProps.currentGoogleUser, userId: nextProps.currentUser.id });
    }

    if (nextProps.calendarEvents && nextProps.calendarEvents.details) {
      const events = [];
      for (const item of nextProps.calendarEvents.details.items) {
        if (item.start && item.end) {
          events.push({
            id: item.id,
            title: item.summary,
            start: moment(item.start.dateTime || item.start.date),
            end: moment(item.end.dateTime || item.end.date),
          });
        }
      }
      this.setState({ events });
    }

    if (!nextProps.addEventProcess.isSubmitting && this.props.addEventProcess.isSubmitting) {
      this.hideEventModal();
    }

    if (!nextProps.editEventProcess.isSubmitting && this.props.editEventProcess.isSubmitting) {
      this.hideEventModal();
    }
  }

  onSuccess(ev) {
    const { submitGoogleAuth, currentUser } = this.props;
    submitGoogleAuth(currentUser.id, { ...ev.tokenObj, profileEmail: ev.profileObj.email });
  }

  onFailure(ev) {
    console.log('onFailure', ev);
  }

  moveEvent({ event, start, end, isAllDay: droppedOnAllDaySlot }) {
    const { currentUser, editGoogleCalendarEvent, calendarEvents } = this.props;
    const { events } = this.state;
    let onlyDate = false;

    const idx = events.indexOf(event);
    const eventIndex = _.findIndex(calendarEvents.details.items, { id: event.id });
    let allDay = event.allDay;
    if (!event.allDay && droppedOnAllDaySlot) {
      allDay = true;
    } else if (event.allDay && !droppedOnAllDaySlot) {
      allDay = false;
    }

    const updatedEvent = { ...event, start, end, allDay };

    const nextEvents = [...events];
    nextEvents.splice(idx, 1, updatedEvent);
    if (eventIndex !== -1) {
      const item = calendarEvents.details.items[eventIndex];
      if (item.start.date && item.end.date) {
        updatedEvent.start = moment(start).format('YYYY-MM-DD');
        updatedEvent.end = moment(end).format('YYYY-MM-DD');
        onlyDate = true;
      }
    }

    this.setState({
      events: nextEvents,
    }, () => {
      editGoogleCalendarEvent({ ...updatedEvent, userId: currentUser.id, timezone: currentUser.timezone, onlyDate });
    });
  }

  editEvent(event) {
    const { currentUser, editGoogleCalendarEvent, calendarEvents } = this.props;
    const { events } = this.state;
    let onlyDate = false;

    console.log('event', event);
    console.log('calendarEvents', calendarEvents);
    const idx = events.indexOf(event);
    const eventIndex = _.findIndex(calendarEvents.details.items, { id: event.id });
    const editedEvent = { ...event };
    console.log('Event Index', eventIndex);
    const nextEvents = [...events];
    nextEvents.splice(idx, 1, editedEvent);
    if (eventIndex !== -1) {
      const item = calendarEvents.details.items[eventIndex];
      if (item.start.date && item.end.date) {
        editedEvent.start = moment(event.start).format('YYYY-MM-DD');
        editedEvent.end = moment(event.end).format('YYYY-MM-DD');
        onlyDate = true;
      }
    }

    this.setState({
      events: nextEvents,
    }, () => {
      console.log('Object', { id: event.event.id, title: event.formValues.title, userId: currentUser.id, timezone: currentUser.timezone, onlyDate });
      editGoogleCalendarEvent({
        id: event.event.id,
        start: moment(event.event.start).hours(event.formValues.period === 'AM' ? event.formValues.hour % 12 : (event.formValues.hour % 12) + 12).minutes(event.formValues.minute).toISOString(),
        end: moment(event.event.end).hours(event.formValues.period === 'AM' ? event.formValues.hour % 12 : (event.formValues.hour % 12) + 12).minutes(event.formValues.minute).toISOString(),
        title: event.formValues.title,
        userId: currentUser.id,
        timezone: currentUser.timezone,
        onlyDate,
      });
    });
  }

  resizeEvent = ({ event, start, end }) => {
    const { events } = this.state;

    const nextEvents = events.map(existingEvent => {
      return existingEvent.id === event.id
        ? { ...existingEvent, start, end }
        : existingEvent;
    });

    this.setState({
      events: nextEvents,
    });

    // console.log(`${event.title} was resized to ${start}-${end}`);
  }

  newEvent(params) {
    const { currentUser, addGoogleCalendarEvent } = this.props;
    const { event, formValues } = params;

    const newEvent = {
      title: formValues.title,
      description: formValues.description ? formValues.description : null,
      allDay: event.slots.length === 1,
      start: moment(event.start).hours(formValues.period === 'AM' ? formValues.hour % 12 : (formValues.hour % 12) + 12).minutes(formValues.minute).toISOString(),
      end: moment(event.end).hours(formValues.period === 'AM' ? formValues.hour % 12 : (formValues.hour % 12) + 12).minutes(formValues.minute).toISOString(),
    };
    this.setState({
      calendarEvent: null,
    }, () => {
      addGoogleCalendarEvent({ ...newEvent, userId: currentUser.id, timezone: currentUser.timezone });
    });
  }

  showEventModal(event) {
    this.setState({ calendarEvent: event, show: true });
  }

  showEditEventModal(event) {
    const { calendarEvents } = this.props;
    const eventIndex = _.findIndex(calendarEvents.details.items, { id: event.id });
    const item = calendarEvents.details.items[eventIndex];
    this.setState({ calendarEvent: item, editShow: true });

  }

  hideEventModal() {
    const { resetForm } = this.props;
    this.setState({ show: false, calendarEvent: null }, () => {
      resetForm();
    });
  }

  hideEditEventModal() {
    const { resetEditForm } = this.props;
    this.setState({ editShow: false, calendarEvent: null }, () => {
      resetEditForm();
    });
  }

  render() {
    const { currentGoogleUser, addEventProcess, editEventProcess } = this.props;
    let authorized = false;

    if (currentGoogleUser && currentGoogleUser.expires_at) {
      authorized = moment(currentGoogleUser.expires_at).isAfter(moment());
    }

    return (
      <div>
        <div className="container-fluid">
          <Helmet title={translate('portals.page.calendarPage.helmetTitle')} />
          <section className="calendar-section">
            <h2 className="main-heading">{translate('portals.page.calendarPage.pageTitle')}</h2>
            {!authorized &&
              <GoogleLogin
                clientId={GOOGLE_CLIENT_ID}
                scope="https://www.googleapis.com/auth/calendar"
                className="google-login"
                onSuccess={this.onSuccess}
                onFailure={this.onFailure}
              >
                <i className="google-image" />
                <span> Sign in with Google</span>
              </GoogleLogin>
            }
            {authorized &&
              <DragAndDropCalendar
                selectable
                events={this.state.events}
                localizer={localizer}
                onEventDrop={this.moveEvent}
                resizable
                onEventResize={this.resizeEvent}
                onSelectSlot={this.showEventModal}
                onSelectEvent={this.showEditEventModal}
                defaultView={BigCalendar.Views.MONTH}
                defaultDate={new Date()}
                views={{ month: true }}
              />
            }

            <AddCalendarEventForm
              show={this.state.show}
              isSubmitting={addEventProcess.isSubmitting}
              calendarEvent={this.state.calendarEvent}
              onSubmit={this.newEvent}
              onHide={this.hideEventModal}
            />

            <EditCalendarEventForm
              show={this.state.editShow}
              isSubmitting={editEventProcess.isSubmitting}
              calendarEvent={this.state.calendarEvent}
              onSubmit={this.editEvent}
              onHide={this.hideEditEventModal}
            />
          </section>
        </div>
      </div>
    );
  }
}

1 个答案:

答案 0 :(得分:-1)

const eventIndex = _.findIndex(calendarEvents.details.items, { id: event.id }); 显然,有一个名为_的数组,我在代码中的任何地方都看不到它,您应该更改执行findIndex()方法的方式。

诸如calendarEvents.details.items.findIndex({id: event.id})

但是,我不认为有这种方法可以在对象内部找到prop值。

您可能想循环播放。