读取目录中的文件 - Expo FileSystem

S.B*_*S.B 1 react-native expo

我使用下面的代码从 API 下载选定的 PDF 文档:

DownloadDocument = (docUri) => {

FileSystem.makeDirectoryAsync(FileSystem.documentDirectory + 'app_docs/', { intermediates: true });

FileSystem.downloadAsync(
  ' https://example.com/library/documents/' + docUri,
  FileSystem.documentDirectory + 'app_docs/' + docUri
)
  .then(({ uri }) => {
    console.log('Finished downloading to ', uri);
  })
  .catch(error => {
    console.error(error);
  });

}
Run Code Online (Sandbox Code Playgroud)

有没有办法可以循环所有已下载到 app_docs 文件夹中的文档?

我一直在尝试使用FileSystem.readDirectoryAsync(FileSystem.documentDirectory + 'app_docs')但没有太多乐趣。

S.B*_*S.B 6

我通过执行以下操作解决了该问题:

state = {
  docsList: [],
}

 componentDidMount() {
   this._getAllFilesInDirectory();
 }

_getAllFilesInDirectory = async() => {
   let dir = await FileSystem.readDirectoryAsync(FileSystem.documentDirectory + 'app_docs');

   dir.forEach((val) => {
     this.state.docsList.push(FileSystem.documentDirectory + 'app_docs/' + val);
});

   await this.setState({docsList: this.state.docsList, loading: false});
}
Run Code Online (Sandbox Code Playgroud)

然后在渲染中:

    {this.state.docsList.map((val, key) => (
        <Text key={key}>{val}</Text>
    ))}
Run Code Online (Sandbox Code Playgroud)

这是一个基本示例,可以帮助那些努力直接从目录文件夹中获得循环工作的人。希望它有帮助。