Получение данных, возвращаемых ReactJS - PullRequest
1 голос
/ 16 апреля 2020

Записывает даты начала и окончания, которые я подготовил во вложении к экрану с console.log; нет проблем, но как я могу передать это с this.setState?

Я хочу перенести даты, записанные на экран console.log, в this.setState. как я могу это сделать?

Дата написана на экране консоли. Я хочу передать с помощью setState

для кодов и ящиков

A this.setstat ({
       date: startViewDateComputed
})

Поэтому я хочу перенести данные, записанные на экран консоли

или как мне получить startViewDateComputed дата отсюда?

коды и поле

1 Ответ

1 голос
/ 17 апреля 2020

Ниже приведена демонстрационная версия вашего решения. js

import * as React from "react";
import Paper from "@material-ui/core/Paper";
import { Plugin, Getter } from "@devexpress/dx-react-core";
import { ViewState } from "@devexpress/dx-react-scheduler";
import {
  Scheduler,
  WeekView,
  Appointments,
  Toolbar,
  ViewSwitcher,
  MonthView,
  DayView
} from "@devexpress/dx-react-scheduler-material-ui";

import { appointments } from "../../../demo-data/month-appointments";

const pluginDependencies = [
  { name: "DayView", optional: true },
  { name: "MonthView", optional: true },
  { name: "WeekView", optional: true },
  { name: "ViewState", optional: true }
];

// modified this component to accept startViewDateComputed and endViewDateComputed
const IntegratedDates = ({ startViewDateComputed, endViewDateComputed }) => {
  return (
    <Plugin dependencies={pluginDependencies} name="IntegratedDates">
      <Getter name="startViewDate" computed={startViewDateComputed} />
      <Getter name="endViewDate" computed={endViewDateComputed} />
    </Plugin>
  );
};
export default class Demo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      startDate: null,
      endDate: null
    };
  }

  // added this 
  shouldComponentUpdate(nextProps, nextState) {
    if (
      nextState.startDate === this.state.startDate &&
      nextState.endDate === this.state.endDate
    ) {
      return false;
    }
    return nextProps === this.props && nextState === this.state;
  }

  //moved this inside class
  startViewDateComputed = ({ startViewDate }) => {
    this.setState(prev => ({ startDate: startViewDate }), ()=> console.log(this.state));
    console.log("start view date:", startViewDate);
    return startViewDate;
  };

  //moved this inside class
  endViewDateComputed = ({ endViewDate }) => {
    this.setState(prev => ({ endDate: endViewDate }), ()=> console.log(this.state));
    console.log("end view date:", endViewDate);
    return endViewDate;
  };

  render() {
    return (
      <Paper>
        <Scheduler data={appointments} height={660}>
          <ViewState
            defaultCurrentDate="2018-07-25"
            defaultCurrentViewName="work-week"
          />

          <WeekView startDayHour={10} endDayHour={19} />
          <WeekView
            name="work-week"
            displayName="Work Week"
            excludedDays={[0, 6]}
            startDayHour={9}
            endDayHour={19}
          />
          <MonthView />
          <DayView />

          {/* modified to pass props */}
          <IntegratedDates
            startViewDateComputed={this.startViewDateComputed}
            endViewDateComputed={this.endViewDateComputed}
          />

          <Toolbar />
          <ViewSwitcher />
          <Appointments />
        </Scheduler>
      </Paper>
    );
  }
}

--- это должно выдавать предупреждение при попытке обновить состояние в методе рендеринга, чтобы избежать замены операторов, обновляющих состояние, на вызов функции, как показано ниже -

  onEndDateUpdated = (endDate) =>  {
    console.debug ('endDateReceived', endDate);
  }
  onStartDateUpdated = (startDate) => { 
    console.debug('startDate');
  }
  //moved this inside class
  startViewDateComputed = ({ startViewDate }) => {
    this.onStartDateUpdated(startViewDate);
    console.log("start view date:", startViewDate);
    return startViewDate;
  };

  //moved this inside class
  endViewDateComputed = ({ endViewDate }) => {
    this.onEndDateUpdated(endViewDate);
    console.log("end view date:", endViewDate);
    return endViewDate;
  };
...