reactjs - react - 上传图片并将上传路径 URL 附加到数据库条目
问题描述
使用 react/redux 工具包
我有一个项目创建屏幕,它上传项目的图像,然后在我的数据库中为该项目创建一个条目。
数据库值之一是 imageURL,它应该指向最近上传的图像。
我有一个有状态的 imageURL 值,应该在文件上传后但在分派创建数据库条目之前将其更改为正确的路径,但我无法在分派发生之前设置 imageURL。
我已经尝试过 useEffect 和 async 但它的 imageURL 似乎只在调度后设置。
const [imageURL, setImageURL] = useState('');
//File upload handler
const uploadFileHandler = async (file) => {
const formData = new FormData();
formData.append('image', file);
setUploading(true);
try {
const config = {
headers: {
'Content-Type': 'multipart/form-data',
},
};
const fileURL = await axios.post('/api/upload', formData, config);
setUploading(false);
return fileURL.data; //this is the path of the uploaded file
} catch (error) {
console.error(error);
setUploading(false);
}
};
//TODO: Submit handler
const submitHandler = async (e) => {
e.preventDefault();
let path = await uploadFileHandler(uploadFile); //this should give me the URL from the upload
setImageURL(path); //this should set the Image URL to the above value, but does not
dispatch(createItem(data, headers));
};
如果有人知道如何解决这个问题,我将不胜感激。
谢谢
解决方案
它不会起作用,因为setImageURL
并且dispatch
在相同的功能上。发生的情况是它首先在设置图像 URL 之前完成该功能。
您可以做的是将其作为“数据”插入到调度中,例如:
const submitHandler = async (e) => {
e.preventDefault();
let path = await uploadFileHandler(uploadFile);
dispatch(createItem({
...data,
image_url: path, // idk if this is the correct property name on the data
}, headers));
};
或者使用useEffect
钩子:
const submitHandler = async (e) => {
e.preventDefault();
let path = await uploadFileHandler(uploadFile);
setImageURL(path);
};
useEffect(() => {
if (imageURL !== '') {
dispatch(createItem(data, headers));
}
}, [imageURL]);
如果 imageURL 发生变化,这种方式将触发调度。
推荐阅读
- sql-server - 再生水系统 1 年的每周平均压力数据
- view - Odoo 13 如何默认扩展附件?
- c# - 应用程序在哪里存储 user.config?
- php - 当表单采取行动时,我的 $_POST 变量变为 NULL
- python - Flask-SQLAlchemy PostgreSQL 获取 AttributeError: 'NoneType' 对象没有属性 'drivername'
- angular - Angular 8 警报或确认功能在(单击)代码部分中没有任何作用
- javascript - 查询关闭选择上的动画汉堡按钮
- python - 如何根据两个变量的条件打印特定输出
- python - 将字符串输出解析为 python 数据结构
- gruntjs - grunt 中的源映射(babel + terser)