我正在嘗試從具有onSnapshot()事件的函式回傳值,但不斷收到這個奇怪的錯誤。基本上,我呼叫此操作并從中回傳資料,就像在任何其他函式中一樣。但我不斷收到這個錯誤,我不知道如何解決它。
這是錯誤
Uncaught TypeError: Cannot add property 0, object is not extensible
at Array.push (<anonymous>)
這個功能
export const getQuestions = () => {
var questions = [];
onSnapshot(collection(firebaseDatabase, "questions"), (querySnapshot) => {
querySnapshot.docs.forEach((doc) => {
if (doc.data() !== null) {
questions.push(doc.data());
}
});
});
return questions;
};
此功能也與Redux Thunk和一起使用Redux Toolkit。
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import { getQuestions } from "../../utils/firebase-functions/firebase-functions";
export const getAllQuestions = createAsyncThunk(
"allQuestions/getAllQuestions",
async () => {
const response = getQuestions();
return response;
}
);
export const allQuestionsSlice = createSlice({
name: "allQuestions",
initialState: {
allQuestions: [],
loading: false,
error: null,
},
extraReducers: {
[getAllQuestions.pending]: (state) => {
state.loading = true;
state.error = null;
},
[getAllQuestions.fulfilled]: (state, action) => {
state.allQuestions = action.payload;
state.loading = false;
state.error = null;
},
[getAllQuestions.rejected]: (state, action) => {
state.loading = false;
state.error = action.payload;
},
},
});
export default allQuestionsSlice.reducer;
發送到哪里
const dispatch = useDispatch();
const tabContentData = useSelector(
(state) => state.allQuestions.allQuestions
);
useEffect(() => {
dispatch(getAllQuestions());
}, [dispatch]);
console.log(tabContentData);
uj5u.com熱心網友回復:
您可以嘗試在第一次獲取資料時回傳一個承諾,如下所示:
let dataFetched = false;
export const getQuestions = () => {
return new Promise((resolve, reject) => {
onSnapshot(collection(firebaseDatabase, "questions"), (querySnapshot) => {
querySnapshot.docs.forEach((doc) => {
if (doc.data() !== null) {
questions.push(doc.data());
}
});
if (!dataFetched) {
// data was fetched first time, return all questions
const questions = querySnapshot.docs.map(q => ({ id: q.id, ...q.data()}))
resolve(questions)
dataFetched = true;
} else {
// Questions already fetched,
// TODO: Update state with updates received
}
});
})
};
getQuestions()現在回傳一個 Promise 所以在這里添加一個等待:
const response = await getQuestions();
對于以后收到的更新,您必須直接在您所在的州進行更新。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/449814.html
標籤:javascript 反应 火力基地 谷歌云火库
