React Native如何实现多张照片上传及从接口拉取数据生成照片列表
React Native 多图上传+列表渲染实现方案
现有代码核心问题
- 当前请求的是单张静态图片资源地址,返回的是图片二进制流,调用
response.json()会直接报错,且没有请求返回多图列表的后端接口 - FlatList绑定的
data属性使用了未定义的list变量,没有和接口返回的列表数据关联 - state中仅存储了单条字符串数据,没有用数组格式存储多图列表
- 字段名存在拼写错误:
describtion应为description
修复后多图拉取渲染代码
export class CustomPhotoModal extends Component { state = { photoList: [], // 存储多图列表的数组 loading: true }; componentDidMount(){ // 替换为你自己的后端多图列表接口地址 fetch("你的后端多图列表接口地址", {method:"GET"}) .then ((response)=> response.json()) .then ((json)=> { // 假设接口返回的数组字段为data this.setState({ photoList: json.data, loading: false }) }) .catch(err => { console.log('拉取列表失败', err) this.setState({loading: false}) }) } render() { if(this.state.loading) { return <SafeAreaView><Text>加载中...</Text></SafeAreaView> } return ( <SafeAreaView style={{ flex: 1 }}> <View style={styles.container}> <FlatList data={this.state.photoList} // 绑定state里的列表数据 keyExtractor={item => item.id.toString()} // 加唯一key避免警告 renderItem={({ item }) => ( <View style={styles.ModalContainerView}> <ImageModal source={{uri: item.photo}} // 绑定图片地址 /> <View> <Text>Designer: {item.name}</Text> <Text>{item.description}</Text> </View> </View> )} /> </View> </SafeAreaView> ); } }
多图上传功能实现
- 安装图片选择依赖
npm install react-native-image-picker --save # 或yarn add react-native-image-picker
- 配置对应平台的相册/相机权限,iOS在info.plist添加相册访问权限,Android在AndroidManifest.xml添加存储访问权限
- 添加上传逻辑代码示例
// 选择多图方法 selectMultiplePhotos = () => { launchImageLibrary({ mediaType: 'photo', selectionLimit: 0, // 0代表不限制选择数量 }, (response) => { if (response.didCancel) return if (response.errorCode) { console.log('选图错误', response.errorMessage) return } // 调用上传方法 this.uploadPhotos(response.assets) }) } // 批量上传方法 uploadPhotos = async (photoAssets) => { const formData = new FormData() photoAssets.forEach((photo, index) => { formData.append('photos[]', { uri: photo.uri, type: photo.type, name: `photo_${index}.${photo.uri.split('.').pop()}` }) // 可同时传其他参数 formData.append('name', '上传的设计师名') formData.append('description', '图片描述') }) // 替换为你的后端上传接口地址 fetch('你的后端多图上传接口地址', { method: 'POST', body: formData, headers: { 'Content-Type': 'multipart/form-data' } }).then(res => res.json()) .then(res => { console.log('上传成功', res) // 上传成功后重新拉取列表刷新 this.componentDidMount() }) .catch(err => console.log('上传失败', err)) }
注意:后端接口需要适配
multipart/form-data格式的请求,接收多图文件后存储并返回对应访问地址,存入数据库后给列表接口返回对应数组数据即可。
内容的提问来源于stack exchange,提问作者Unico
相关产品推荐
相关产品推荐

