【发布时间】:2021-06-07 11:49:09
【问题描述】:
使用 react/redux 工具包
我有一个项目创建屏幕,它上传项目的图像,然后在我的数据库中为该项目创建一个条目。
其中一个数据库值是 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?是useStatesetter 还是 redux 操作?如果它是一个 redux 操作,你有什么理由不调用dispatch吗? -
哦,对不起,在我的代码复制/粘贴中遗漏了。这是一个二传手:
const [imageURL, setImageURL] = useState(''); -
看起来应该可以了。 “这应该将图像 URL 设置为上述值,但没有”是什么意思?您希望它在哪里看到和看不到?
-
感谢您的帮助,在下面回答。
标签: reactjs mongoose redux-toolkit