自定义钩子错误:只能在函数组件的主体内部调用钩子

时间:2019-09-28 00:50:55

标签: javascript reactjs typescript ecmascript-6

我正在尝试开发一个自定义钩子,这似乎很简单,但出现错误

  

未捕获的永久违反:无效的挂接调用。挂钩只能在功能组件的主体内部调用。发生这种情况可能是由于以下原因之一:

     
      
  1. 您可能使用的React和渲染器版本不匹配(例如React DOM)
  2.   
  3. 您可能正在违反挂钩规则
  4.   
  5. 您可能在同一应用中拥有多个React副本
  6.   

这是我的钓钩:

import React, { useState, useEffect } from 'react';

const useInfiniteScroll = (isLastPage: boolean, fetchFn: any) => {
  const [pageCount, setPageCount] = useState(0);
  const triggerFetchEvents = (): void => {
    let response;

    setPageCount(() => {
      if (!isLastPage) {
        response = fetchFn(pageCount + 1, 5, 'latest');
      }

      return pageCount + 1;
    });

    return response;
  };

  useEffect(() => {
    triggerFetchEvents();
  }, []);

  return pageCount;
};

export default useInfiniteScroll;

这里我称之为组件:

import React, { FC } from 'react';
import { connect } from 'react-redux';
import { fetchEvents } from '../../shared/actions/eventActions';
import { AppState } from '../../shared/types/genericTypes';
import EventModel from '../../shared/models/Event.model';
import EventListPage from '../../components/events/EventListPage';
import useInfiniteScroll from '../../shared/services/triggerInfiniteScroll';

type Props = {
  fetchEvents?: any;
  isLastPage: boolean;
  eventsList?: EventModel[];
};

const mapState: any = (state: AppState, props: Props): Props => ({
  eventsList: state.eventReducers.eventsList,
  isLastPage: state.eventReducers.isLastPage,
  ...props
});

const actionCreators = {
  fetchEvents
};

export const EventsScene: FC<Props> = props => {
  const { eventsList, fetchEvents, isLastPage } = props;
  const useIn = () => useInfiniteScroll(isLastPage, fetchEvents);

  useIn();

  // const [pageCount, setPageCount] = useState(0);

  // const triggerFetchEvents = (): void => {
  //   let response;

  //   setPageCount(() => {
  //     if (!isLastPage) {
  //       response = fetchEvents(pageCount + 1, 1, 'latest');
  //     }

  //     return pageCount + 1;
  //   });

  //   return response;
  // };

  // useEffect(() => {
  //   triggerFetchEvents();
  // }, []);

  if (!eventsList || !eventsList.length) return null;

  return (
    <EventListPage
      eventsList={eventsList}
      isLastPage={isLastPage}
      triggerFetchEvents={useIn}
    />
  );
};

export default connect(
  mapState,
  actionCreators
)(EventsScene);

我在这里留下了注释的代码,向您显示,如果我取消注释代码并删除useInfiniteScroll,那么它将正常工作。

我可能会缺少什么?

更新: 这是EventListPage组件

import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import EventModel from '../../shared/models/Event.model';
import { formatDate } from '../../shared/services/date';
import Container from 'react-bootstrap/Container';
import Row from 'react-bootstrap/Row';
import Col from 'react-bootstrap/Col';
import Card from 'react-bootstrap/Card';

type Props = {
  eventsList?: EventModel[];
  isLastPage: boolean;
  triggerFetchEvents: any;
};

export const EventListPage: React.FC<Props> = props => {
  const { eventsList, triggerFetchEvents, isLastPage } = props;

  const [isFetching, setIsFetching] = useState(false);

  const fetchMoreEvents = (): Promise<void> =>
    triggerFetchEvents().then(() => {
      setIsFetching(false);
    });

  const handleScroll = (): void => {
    if (
      document.documentElement.offsetHeight -
        (window.innerHeight + document.documentElement.scrollTop) >
        1 ||
      isFetching
    ) {
      return;
    }

    return setIsFetching(true);
  };

  useEffect(() => {
    if (isFetching) return;

    window.addEventListener('scroll', handleScroll);

    return () => {
      window.removeEventListener('scroll', handleScroll);
    };
  }, []);

  useEffect(() => {
    if (!isFetching) return;

    if (!isLastPage) fetchMoreEvents();
  }, [isFetching]);

  if (!eventsList) return null;

  return (
    <Container className='article-list mt-5'>
      ///...
    </Container>
  );
};

export default EventListPage;

1 个答案:

答案 0 :(得分:0)

EventsScene中,将useInfiniteScroll更改为直接在函数主体的顶层直接调用(不确定为什么首先要创建此间接调用):

// before
const useIn = () => useInfiniteScroll(isLastPage, fetchEvents);
useIn();

// after
useInfiniteScroll(isLastPage, fetchEvents)

React期望仅对happen at the top-level的Hook调用,因为它依赖于Hook的顺序始终相同。如果将挂钩包装在函数中,则可能会在许多代码位置调用该函数,从而扰乱挂钩的顺序。

  

每个组件都有一个内部的“内存单元”列表。它们只是JavaScript对象,我们可以在其中放置一些数据。当您调用类似于useState()的Hook时,它将读取当前单元格(或在第一个渲染期间将其初始化),然后将指针移至下一个单元格。这是多个useState()调用的方式分别获得独立的本地状态。 Link