reactjs - 使用效果未按预期调用
问题描述
我正在尝试在 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]
但不会调用效果。我在这里做错了什么?
解决方案
currentChunkIndex
从 更改null
为0
,您仅将其设置为0
。
useEffect(() => {
if (files.length > 0) {
console.log('got a file');
setCurrentChunkIndex(files.length);
}
}, [files]);
推荐阅读
- python - Pyplot 绘制索引而不是数据框的值
- python-3.x - 我们如何将flask后端与react.js前端打包并将其作为桌面应用程序(.exe、.dmg、.tar等)交付
- c - 为什么它总是重新运行-1
- php - jquery数据表搜索php [codeigniter]不工作
- java - setOnClickListener 和 setOnLongClickListener 不能同时工作
- python - 如何将 cloudant.document 转换为 json
- redis - Redis rejson 或字符串
- pivot - 动态列上的多个枢轴
- python - 如何测试接受输入的类方法?
- c - C 线程程序:为什么这段代码给了我“重新声明为不同类型的符号”错误?