gpt4 book ai didi

javascript - 如何使用 useState 然后在 React 中执行具有最新状态的函数?

转载 作者:行者123 更新时间:2023-12-01 00:52:22 26 4
gpt4 key购买 nike

我正在使用 useState 来管理组件的状态。我需要创建状态,然后执行一个函数来使用组件的状态调用我的 API。

我尝试这样做:

const [uploadedFile, setUploadedFile] = useState(null);

const handleUpload = file => {
const upload = {
file: file[0],
name: file[0].name,
preview: URL.createObjectURL(file[0]),
progress: 0,
uploaded: false,
error: false,
url: null
};
setUploadedFile(upload);
processUpload(file[0]);
};

const processUpload = file => {
const data = new FormData();

data.append("file", file, file.name);

api
.put("/Private/user/documentupload", data, {
onUploadProgress: e => {
const progress = parseInt(Math.round((e.loaded * 100) / e.total));
setUploadedFile({ ...uploadedFile, progress });
}
})
.then(response => {
console.log(response);
setUploadedFile({
...uploadedFile,
uploaded: true,
url: response.data.identity.url
});
})
.catch(error => {
setUploadedFile({ ...uploadedFile, error: true });
});
};

但是,当调用processUpload(file[0])时,组件的状态为null(初始状态)。我尝试使用 useEffect:

const [uploadedFile, setUploadedFile] = useState(null);

const handleUpload = file => {
const upload = {
file: file[0],
name: file[0].name,
preview: URL.createObjectURL(file[0]),
progress: 0,
uploaded: false,
error: false,
url: null
};
setUploadedFile(upload);
};

useEffect(() => {
processUpload(uploadedFile.file);
}, [uploadedFile]);

const processUpload = file => {
const data = new FormData();

data.append("file", file, file.name);

api
.put("/Private/user/documentupload", data, {
onUploadProgress: e => {
const progress = parseInt(Math.round((e.loaded * 100) / e.total));
setUploadedFile({ ...uploadedFile, progress });
}
})
.then(response => {
console.log(response);
setUploadedFile({
...uploadedFile,
uploaded: true,
url: response.data.identity.url
});
})
.catch(error => {
setUploadedFile({ ...uploadedFile, error: true });
});
};

但这不起作用,因为当组件首次渲染时,uploadedFile 为 null。我该如何处理这个问题?

提前致谢

最佳答案

编辑handleUpload 开始上传:

const handleUpload = file => {
const upload = {
file: file[0],
name: file[0].name,
preview: URL.createObjectURL(file[0]),
progress: 0,
uploaded: false,
error: false,
url: null
};
setUploadedFile(upload);
processUpload(file[0]);
};

或者检查upload.file,而不仅仅是upload:

useEffect(() => {
if (uploadedFile) {
processUpload(uploadedFile.file);
}
}, [uploadedFile && uploadedFile.file]);

在这种情况下,仅当文件实际更改时才会重新触发。但我可能只会从处理程序中调用上传。

旧答案:

useEffect 中添加检查:

useEffect(() => {
if (uploadedFile) {
processUpload(uploadedFile.file);
}
}, [uploadedFile]);

关于javascript - 如何使用 useState 然后在 React 中执行具有最新状态的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56873518/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com