首页 > 解决方案 > 使用效果未按预期调用

问题描述

我正在尝试在 React 中实现一个简单的文件上传放置区:

import { useState, useEffect } from 'react';
import './App.css';

const  App = () => {
  const [isDropzoneActive, setIsDropzoneActive] = useState(false);
  const [files, setFiles] = useState([]);
  const [currentChunkIndex, setCurrentChunkIndex] = useState(null);

  const handleDragOver = e => {
    e.preventDefault();
    setIsDropzoneActive(true);
  };

  const handleDragLeave = e => {
    e.preventDefault();
    setIsDropzoneActive(false);
  };

  // Update the files array
  const handleDrop = e => {
    e.preventDefault();

    setIsDropzoneActive(false);
    // Just overwrite for this simple example
    setFiles(e.dataTransfer.files);
  };

  // Monitor the files array
  useEffect(() => {
    if (files.length > 0) {
      console.log('got a file');

      setCurrentChunkIndex(0);
    }
  }, [files]);

  // Monitor the chunk index
  useEffect(() => {
    if (currentChunkIndex !== null) {
      readAndUploadCurrentChunk();
    }
  }, [currentChunkIndex]);

  const readAndUploadCurrentChunk = () => {
    // Implement later
  };

  return (
    <div
      onDragOver={handleDragOver}
      onDragLeave={handleDragLeave}
      onDrop={handleDrop}
      className={"dropzone" + (isDropzoneActive ? " active" : "")}
    >
        {files.length > 0 ? 'Uploading' : 'Drop your files here'}
    </div>
  );
}

export default App;

但是,似乎[currentChunkIndex]没有正确调用监视器的效果。我试图将文件一个一个拖入放置区。[files]每次都正确调用它的效果,[currentChunkIndex]但不会调用效果。我在这里做错了什么?

标签: reactjsuse-effect

解决方案


currentChunkIndex从 更改null0,您仅将其设置为0

  useEffect(() => {
    if (files.length > 0) {
      console.log('got a file');

      setCurrentChunkIndex(files.length);
    }
  }, [files]);

推荐阅读