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));
};

如果有人知道如何解决这个问题,我将不胜感激。

感谢

它不会工作,因为setImageURLdispatch在同一个函数上。结果是它首先完成了设置图像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发生更改,就会触发调度。

最新更新