TypeError:无法解构“ Object(...)(...)”的属性“ isLoading”,因为它未定义

时间:2020-04-01 03:33:10

标签: reactjs react-hooks

我想在使用React请求API的同时构建一个加载微调器,我在React中使用上下文来获取API,并在上下文中进入def loads(s, *, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw): """Deserialize ``s`` (a ``str``, ``bytes`` or ``bytearray`` instance containing a JSON document) to a Python object. ... """ if isinstance(s, str): if s.startswith('\ufeff'): raise JSONDecodeError("Unexpected UTF-8 BOM (decode using utf-8-sig)", s, 0) else: if not isinstance(s, (bytes, bytearray)): raise TypeError(f'the JSON object must be str, bytes or bytearray, ' f'not {s.__class__.__name__}') s = s.decode(detect_encoding(s), 'surrogatepass') 状态,但是当我在isLoading中调用isLoading时。它具有错误TypeError:无法解构“ Object(...)(...)”的属性“ isLoading”,因为它是未定义的。 context.js

App.js

App.js

/* eslint-disable react/prop-types */
/* eslint-disable no-underscore-dangle */
import React, { useState, useEffect, createContext, useCallback } from 'react';
import moment from 'moment';

import { getResource } from '../api/resourceApi';
import { getProject } from '../api/projectApi';
import { getBooking, deleteBooking, updateBooking } from '../api/bookingApi';
import { HEIGHT_BOOKING } from '../containers/App/constant';
import { compareByDay, getNumberOfDay, isWeekend } from '../utils/Date';

const CalendarContext = createContext();

const CalendarProvider = props => {
  const [isDragLoading, setIsDragLoading] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [persons, setPersons] = useState([]);
  const [projects, setProjects] = useState([]);
  const [search, setSearch] = useState('');
  const [searchResult, setSearchResult] = useState([]);
  const [bookings, setBookings] = useState([]);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [startDay, setStartDay] = useState(moment('2019-12-30', 'YYYY-MM-DD'));
  const [endDay, setEndDay] = useState(moment('2020-02-03', 'YYYY-MM-DD'));
  const [disabled, setDisabled] = useState(false);
  const [isHoverWorking, setIsHoverWorking] = useState(true);
  const [addBookingStatus, setAddBookingStatus] = useState(true);
  const [content, setContent] = useState({
    resource: [],
    booking: undefined,
    startDate: moment(),
    endDate: moment(),
  });
  const [start, setStart] = useState(0);
  const [end, setEnd] = useState(0);
  const [selecting, setSelecting] = useState(false);
  const [resourceStart, setResourceStart] = useState(0);
  const [first, setFirst] = useState(false);
  const [startCellDay, setStartCellDay] = useState(moment());
  const [lastDate, setLastDate] = useState(0);
  const [isHover, setIsHover] = useState(false);
  const [formIsOpening, setFormIsOpening] = useState(false);
  const [bookingId, setBookingId] = useState(null);

  const contentGlobal = () => content;
  const setContentGlobal = newContent => {
    setContent(newContent);
  };
  const hoverObject = {
    start,
    end,
    selecting,
    resourceStart,
    first,
    startCellDay,
    lastDate,
    isHover,
    formIsOpening,
    isHoverWorking,
    addBookingStatus,
  };



  const onDisabled = () => {
    setDisabled(!disabled);
  };
  const fetchResource = async () => {
    setIsLoading(true);
    const res = await getResource();
    const result = res.data.resources;
    const personsFilter = result.map(resource => {
      const person = {
        _id: resource._id,
        name: `${resource.name.first} ${resource.name.last}`,
        avatar: resource.avatar,
      };
      return person;
    });
    setPersons(personsFilter);
    setSearchResult(personsFilter);
    setIsLoading(false);
  };
  const fetchProject = async () => {
    setIsLoading(true);
    const res = await getProject();
    const result = res.data.projects;
    setProjects(result);
    setIsLoading(false);
  };
  const fetchBooking = useCallback(async () => {
    setIsLoading(true);
    const res = await getBooking(startDay, endDay);
    const result = res.data.bookings;
    const bookingsConvert = result.map(booking => {
      const schedule = {
        ...booking,
        project: booking.project,
        startDay: moment(booking.startDay),
        endDay: moment(booking.endDay),
      };
      return schedule;
    });
    setBookings([...bookingsConvert]);
    setIsLoading(false);
  }, [startDay, endDay]);
  const removeBooking = async id => {
    const newBookings = bookings.filter(booking => booking._id !== id);
    await deleteBooking(id);
    setBookings([...newBookings]);
  };

  const handleSetBookings = (booking, onAdd = true) => {
    if (onAdd) {
      setBookings([...bookings, booking]);
    } else {
      const filterBooking = bookings.filter(e => e._id !== booking._id);
      setBookings([...filterBooking, booking]);
    }
  };

  const updateSearch = event => {
    setSearch(event.target.value.toLowerCase());
  };


  function getBookingWithResource(date, indexResource) {
    const bookingsWithResource = bookings
      .filter(booking => {
        const isBookingBelongResource =
          booking.startDay.isSame(date, 'day') &&
          booking.resourceId === searchResult[indexResource]._id;
        return isBookingBelongResource;
      })
      .sort(
        // eslint-disable-next-line no-shadow
        (first, second) => compareByDay(second.endDay, first.endDay),
      );
    return bookingsWithResource;
  }
  useEffect(() => {
    fetchResource();
    return () => {};
  }, []);
  useEffect(() => {
    fetchBooking();
    return () => {};
  }, [fetchBooking]);
  useEffect(() => {
    fetchProject();
    return () => {};
  }, []);
  useEffect(() => {
    const filteredResults = persons.filter(
      item => item.name.toLowerCase().indexOf(search) !== -1,
    );
    setSearchResult(filteredResults);
  }, [search, persons]);
  return (
    <CalendarContext.Provider
      value={{

        persons,
        projects,
        search,
        searchResult,
        updateSearch,
        bookings,
        setBookings,
        fetchBooking,
        handleSetBookings,
        getMaxTotalOverlapBooking,
        getBookingWithResource,
        getMarginTopBooking,
        isModalOpen,
        handleCloseModal,
        setStartDay,
        setEndDay,
        startDay,
        endDay,
        disabled,
        onDisabled,
        removeBooking,
        setBegin,
        updateOnDidDragBooking,
        contentGlobal,
        setContentGlobal,
        start,
        setStart,
        end,
        setEnd,
        selecting,
        setSelecting,
        resourceStart,
        setResourceStart,
        first,
        setFirst,
        startCellDay,
        setStartCellDay,
        lastDate,
        setLastDate,
        isHover,
        setIsHover,
        addBookingStatus,
        setAddBookingStatus,
        formIsOpening,
        hoverObject,
        hoverSetObject,
        isDragLoading,
        setIsDragLoading,
        bookingId,
        isLoading,
      }}
    >
      {props.children}
    </CalendarContext.Provider>
  );
};
export { CalendarProvider, CalendarContext };

1 个答案:

答案 0 :(得分:0)

更改:

value={{

        isLoading,
      }}

使用

value={isLoading}