为反应日历添加编辑表单

时间:2018-11-27 15:00:40

标签: javascript reactjs google-calendar-api redux-saga

我的日历有问题。我可以通过单击特定日期来添加新表单,但是我不知道如何通过单击它来编辑现有表单。

这是日历页面的代码

<?php while($result = $stmt->fetch()): ?>        
<tr>
    <td clas="text-center">#</td>
    <td><?=$id; ?> </td>
    <td><?=$first_name; ?> </td>
    <td><?=$last_name; ?> </td>
    <td class="text-center">Details</td>
</tr>
<?php endwhile; ?>

这是AddCalendarEventForm代码

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 { translate } from '../../../common/utilities/localization';

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

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

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

const formName = 'addCalendarEvent';

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

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

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)),
});

@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,
    resetForm: PropTypes.func,
  };

  constructor(props) {
    super(props);

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

    this.onSuccess = this.onSuccess.bind(this);
    this.onFailure = this.onFailure.bind(this);
    this.moveEvent = this.moveEvent.bind(this);
    this.newEvent = this.newEvent.bind(this);
    this.showEventModal = this.showEventModal.bind(this);
    this.hideEventModal = this.hideEventModal.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();
    }
  }

  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 });
    });
  }

  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 });
  }

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

  render() {
    const { currentGoogleUser, addEventProcess } = 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={(e) => { console.log('e', e); }}
                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}
            />
          </section>
        </div>
      </div>
    );
  }
}

当前,当我单击特定事件时,我可以在控制台中看到一些输出,但是我无法添加表单来编辑该事件。

0 个答案:

没有答案