JavaScript - 将数据传递给具有预定义参数的回调
问题描述:
如果有人能帮助我解决这个问题,我将非常感激。我认为那里可能有一个简单的解决方案,但我无法解决它,这是非常令人沮丧的。JavaScript - 将数据传递给具有预定义参数的回调
我正在使用Expo开发React Native应用程序。他们的SDK具有“downloadResumable”功能,允许用户下载文件。
提供下载进度信息的回调函数获取一个对象'totalBytesWritten',并且'totalBytesExpectedToWrite'道具自动传递给它。
有没有什么办法可以将'songId'参数传递给createDownloadResumable中的回调函数,以便回调函数不需要引用外部'_id'变量?
在此先感谢任何能够帮助我的人!
const { _id } = song;
const callback = ({ totalBytesWritten, totalBytesExpectedToWrite }) => dispatch(updateDownloadProgress(
_id,
totalBytesWritten,
totalBytesExpectedToWrite
));
const createDownloadResumable = songId => FileSystem.createDownloadResumable(
link,
FileSystem.documentDirectory + `${songId}.mp3`,
{},
callback,
);
const downloadResumable = createDownloadResumable(_id);
答
您应该能够通过这样的闭包内创建回调做到这一点:
const { _id } = song;
const generateCallback = (songId) => {
return ({ totalBytesWritten, totalBytesExpectedToWrite }) => dispatch(updateDownloadProgress(
songId,
totalBytesWritten,
totalBytesExpectedToWrite
));
}
const createDownloadResumable = (songId) => FileSystem.createDownloadResumable(
link,
FileSystem.documentDirectory + `${songId}.mp3`,
{},
generateCallback(songId),
);
const downloadResumable = createDownloadResumable(_id);
哎呀,真的挺到最后一个简单的解决方案。但是,我正在寻找的是,非常感谢。非常感激! –