如何在延迟获取数据的同时使React和相交api无限滚动工作?

时间:2020-04-04 13:29:37

标签: javascript reactjs intersection-observer

第一次尝试反应,它是交集API。

我可能缺少一些基础知识。 请在指出错误时进行解释。

我正在尝试通过api调用的延迟加载图像来进行无限滚动。

当我触底时,我又进行了一次api调用以获取更多数据,

以便获得无限滚动。

  if(loading) {
    return <p>Loading data...</p>
  }
  return (

    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <div style={{height: "400px"}}>
        <ul>
          {!loading && data.map((url,index)=> 
            <li><img src={url} alt="" width="200" height="200" /></li>
          )}
        </ul>
      </div>
      <div ref={setElement} style={{background: "transparent"}}>Load More</div>
    </div>
  );

因此,基本上,我只是映射数据,在其中我几乎没有网址,并相应地显示图像。

当我谈到它时,有一个div “加载更多” 。我需要再次显示加载指示器,然后尝试获取数据并显示更多图像等等。

我由useReducer定义的这些状态

const [state, dispatch] = useReducer(reducer, {
    loading: false,
    data: []
  });

const reducer = (state, action) => {
  switch (action.type) {
    case "startLoadingData":
      return {
        ...state,
        loading: true,
        data: []
      };
    case "loadMoreData":
      return {
        ...state,
        loading: false,
        data: state.data.concat(action.payload) // Did it so that I do not mess the existing images on top
      };
    default:
      throw new Error("Cannott parse action");
  }
};

但是我设置interSection apiside effect caused by that的页面进入无限循环的方式。

我也不知道为什么。

  const [element, setElement] = useState(null); // create a ref to the div element at bottom

  const loadData = () => {

      dispatch({type: "startLoadingData"});
      axios.all([axios.get('https://aws.random.cat/meow'),
              axios.get('https://random.dog/woof.json')])
        .then(axios.spread((catResponse, dogResponse) => {  
            console.log(catResponse.data,dogResponse.data);
            let response = [];
            response.push(catResponse.data.file);
            response.push(dogResponse.data.url);
            dispatch({type:"loadMoreData", payload: response})
        }))
        .catch(error => console.log(error));
  }

  const observer = useRef(
      new IntersectionObserver((entries) => {
        let first = entries[0].isIntersecting;
        console.log(first);
        if(first) {
          loadData();
        }
      },{threshold: 1})
  );

  useEffect(() => {
    let currentElement = element;
    let currentObserver = observer.current;
     if(currentElement) {
      currentObserver.observe(element);
    }

    return () => {
      if(currentElement) {
        currentObserver.unobserve(element)
      }
    }  
  },[element]);

每当element依赖项更改时,我都会尝试相同的操作。但不起作用。

请解释我想念的是什么?

在线代码链接:https://stackblitz.com/edit/react-egkdqy

1 个答案:

答案 0 :(得分:0)

似乎可以正常使用

case "loadMoreData":
      return {
        ...state,
        loading: false,
        data: [...state.data, ...action.payload]
      };

当您向下滚动时,它会加载更多的图像,然后再获取两张图像。