【发布时间】:2021-01-11 09:18:07
【问题描述】:
我正在开发一个 React Native 项目。
我想在 useState 钩子中添加多个图像而不重新设置钩子的状态。
例如:我想使用相机捕获图像并使用文件路径更新挂钩(目前可以),然后我想通过相机捕获另一张图像并更新反应挂钩之前的值(需要之前的文件路径和新的文件路径)。
问题是当我尝试捕获新图像并更新 useState 时,useState 挂钩重新渲染视图,它会删除以前的文件路径并存储一个新的文件路径。
我遇到了这个问题,请帮助我找到解决方案。提前致谢。
const tempArray = [];
const [selectedFiles, setSelectedFiles] = useState([]);
// capturing the image --------------
const chooseFile = () => {
const options = {
title: 'Select an option',
storageOptions: {
skipBackup: true,
path: 'images',
},
};
ImagePicker.showImagePicker(options, (response) => {
// console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
onsole.log('ImagePicker Error: ', response.error);
} else {
// let source = response;
// You can also display the image using data:
let source = {
uri: 'data:image/jpeg;base64,' + response.data
};
createImageArray(source);
}
});
};
const createImageArray = (imageData: string) => {
// adding file path to temp array -> to get the selected images
tempArray.push(imageData);
setImagesToHooks();
console.log("tempArray.length : " + tempArray.length);
}
const setImagesToHooks = () => {
const imagesArray = Array.from(tempArray).map((result) => result);
console.log('images : ' + JSON.stringify(imagesArray));
// adding mapped array to state hook
setSelectedFiles(imagesArray);
}
【问题讨论】:
-
请更新您的代码