JavaScript - 使用预定义参数将数据传递给回调

时间:2017-09-04 03:21:04

标签: javascript reactjs react-native expo

如果有人能帮我解决这个问题,我将非常感激。我认为可能有一个简单的解决方案,但我无法解决这个问题,而且非常令人沮丧。

我正在使用Expo开发React Native应用程序。他们的SDK有一个' downloadResumable'允许用户下载文件的功能。

提供下载进度信息的回调函数获取具有" totalBytesWritten'的对象。和  ' totalBytesExpectedToWrite'道具自动传递给它。

我有什么方法可以通过歌曲'我将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);

1 个答案:

答案 0 :(得分:0)

您应该可以通过在闭包中创建回调来实现此目的:

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);
相关问题