求助:使用react-native-document-picker时出现pick of null的TypeError错误
解决react-native-document-picker的"Cannot read property 'pick' of null"错误
1. 重新安装并确认库的链接状态
- 先卸载现有库:
npm uninstall react-native-document-picker # 或 yarn remove react-native-document-picker - 安装最新稳定版:
npm install react-native-document-picker # 或 yarn add react-native-document-picker - React Native 0.60+支持自动链接,旧版本需手动执行:
react-native link react-native-document-picker
2. 完善iOS端配置
- 进入iOS目录执行Pod安装:
cd ios && pod install && cd .. - 在
Info.plist中添加文件访问权限描述:<key>NSDocumentPickerUsageDescription</key> <string>需要访问您的文件以上传PDF</string>
3. 完善Android端配置
- 在
android/app/src/main/AndroidManifest.xml中添加权限:<!-- 基础文件访问权限 --> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <!-- Android 13+ 需额外添加 --> <uses-permission android:name="android.permission.READ_MEDIA_DOCUMENTS" />
4. 适配版本对应的API与导入方式
如果使用的是v8及以上版本,库的API和导入逻辑有调整:
- 导入方式保持正确:
import DocumentPicker, { DocumentPickerResponse } from 'react-native-document-picker'; - v8+版本中
pick方法返回单个对象而非数组,需修改代码逻辑:const pickFile = async () => { try { const res: DocumentPickerResponse = await DocumentPicker.pick({ type: [DocumentPicker.types.pdf], }); Alert.alert( "File Selected", `URI: ${res.uri}\nType: ${res.type}\nName: ${res.name}\nSize: ${res.size}` ); } catch (err) { if (DocumentPicker.isCancel(err)) { console.log("User cancelled the picker"); } else { console.error("Error picking file:", err); Alert.alert("Error", "An error occurred while picking the file."); } } };
5. 清除缓存并重启项目
- 清除React Native缓存:
npx react-native start --reset-cache - 重启模拟器/真机,重新运行项目:
npx react-native run-android # 或 npx react-native run-ios
内容的提问来源于stack exchange,提问作者raks
相关产品推荐
相关产品推荐

