Firebase+Redux开发预约应用触发s.indexOf is not a function报错求解
问题解决方法
TypeError: s.indexOf is not a function 报错的根本原因是你向Firestore的doc()方法传入了非字符串类型的参数,Firestore内部处理文档路径时会对传入的文档ID调用字符串的indexOf方法,传入对象就会触发该错误。
你的代码存在两个核心问题:
- 你传入
updateSeatByDate的参数是包含座位id和occupied状态的对象数组,遍历拿到的element是单个对象,而doc()方法需要传入字符串类型的座位ID,你直接传了整个element对象,触发报错。 - 更新
occupied字段时,你错误读取了数组本身的occupied属性(数组没有该属性),应该读取当前遍历元素的occupied属性。
修正后的代码如下:
export const updateSeatByDate = (seatList) => { return (dispatch, getState, { getFirestore }) => { const firestore = getFirestore(); // 先校验参数类型,避免非数组调用forEach报错 if (!Array.isArray(seatList)) return; seatList.forEach(seatItem => { firestore.collection('Building1').doc('Floor1').collection('Seats1').doc(seatItem.id).update({ occupied: seatItem.occupied }).then(() => { dispatch({ type: 'UPDATED_SEATS'}) }).catch((err) => { dispatch({ type: 'UPDATED_SEATS_ERROR', payload: err}) }) }) } }
优化建议:如果需要同时更新多个座位,建议使用Firestore批量写入(Batch)来减少网络请求,同时保证所有更新操作原子性,避免数据不一致:
export const updateSeatByDate = (seatList) => { return async (dispatch, getState, { getFirestore }) => { const firestore = getFirestore(); if (!Array.isArray(seatList)) return; const batch = firestore.batch(); seatList.forEach(seatItem => { const seatRef = firestore.collection('Building1').doc('Floor1').collection('Seats1').doc(seatItem.id); batch.update(seatRef, { occupied: seatItem.occupied }); }) try { await batch.commit(); dispatch({ type: 'UPDATED_SEATS'}) } catch (err) { dispatch({ type: 'UPDATED_SEATS_ERROR', payload: err}) } } }
内容的提问来源于stack exchange,提问作者Tamás Köböl
相关产品推荐
相关产品推荐

