React Native Expo中如何为Swipeable组件添加状态更新POST API
实现步骤&代码修改
1. 修复Action层的请求逻辑
现有action存在三个问题:请求时没有传入构造好的FormData、Booking_no参数为空、参数keyaction 末尾多了多余空格,修改后代码如下:
export const updateStatus = (bookingNo, collected) => { return async (dispatch) => { const token = await SecureStore.getItemAsync("userToken"); const url = `/update-status`; var formdata = new FormData(); formdata.append("Booking_no", bookingNo); // 传入实际订单号 formdata.append("action", collected ); // 去掉key末尾的多余空格 const response = await api .post(url, formdata, { // 第二个参数传入FormData headers: { Authorization: `Bearer ${token}`, "Content-Type": "multipart/form-data" // 明确formdata请求头 }, }) .then((res) => { return res; }) .catch((error) => { return error.response; }); dispatch({ type: "UPDATE_STATUS", payload: response, }); }; };
2. 组件层绑定滑动事件&状态联动
主要修改点:
- 移除组件内部无用的
showMe状态和相关的定时器,直接使用Redux返回的update_status控制展示逻辑 - 给Swipeable组件绑定
onSwipeableOpen事件,左滑完成后触发状态更新的API请求 - 采集完成后禁用Swipeable滑动,固定展示「样本已采集」状态
修改后的组件核心代码如下:
// 先删除constructor里的showMe状态、componentDidMount里的setTimeout逻辑 render() { const LeftSwipeActions = () => { return ( <View style={[styles.container1, styles.horizontal]}> {!this.props.update_status ? ( <View style={{ alignSelf: "center" }}> <ActivityIndicator size="large" color="#4DB2F8" /> </View> ) : ( <View style={styles.sampleMain}> <Text style={styles.sample}>样本已采集</Text> </View> )} </View> ); }; // ...保留其他原有代码不变 // 底部操作栏部分修改为如下代码 return ( <View style={styles.container} key={bookdata.id}> {/* 保留其他原有布局代码不变 */} {/* 底部操作栏 */} <View style={{ flex: 1, bottom: 0, right: 0, left: 0, position: "absolute", }} > {/* 已采集完成直接展示固定状态,禁止滑动 */} {this.props.update_status ? ( <View style={styles.collectMainMain}> <View style={styles.sampleMain}> <Text style={styles.sample}>样本已采集</Text> </View> </View> ) : ( <Swipeable renderLeftActions={LeftSwipeActions} // 左滑完成后触发API请求 onSwipeableOpen={(direction) => { if (direction === 'left') { this.props.updateStatus(bookdata.booking_no, 'collected') } }} > <View style={styles.collectMainMain}> <MaterialCommunityIcons name="chevron-right" style={styles.material} size={20} /> <View style={styles.collectMain}> <Text style={styles.collect}>Collect Samples</Text> </View> </View> </Swipeable> )} </View> </View> ) }
3. 可选优化
如果需要处理请求失败的情况,可以在action请求失败后添加toast提示,同时重置状态允许用户重新滑动触发操作。
内容的提问来源于stack exchange,提问作者afshana zaman
相关产品推荐
相关产品推荐

