【发布时间】:2022-06-11 18:20:09
【问题描述】:
您好,我有一个问题,我正在使用 Firebase 和 React 制作应用程序。问题是我想要评论数组,但是在创建项目时它是空的。我怎样才能解决这个问题并有一个空数组,然后在添加 cmets 后更新这个数组。
代码很多。
const onSubmitHandler = (e: React.FormEvent): void => {
e.preventDefault();
if (user?.displayName) {
const recipe: Recipe = {
username: user.displayName,
title: title,
type: type,
description: description,
id: Math.random(),
time: time,
ingredients: ingredients,
stars: Math.floor(Math.random() * 6) + 1,
steps: steps,
comments: [],
};
dispatch(recipeAction.addRecipe(recipe));
dispatch(sendData(recipe));
navigate("/");
}
};
Redux action
export const fetchRecipes = () => {
return async (dispatch: ThunkDispatch<{}, {}, AnyAction>) => {
dispatch(uiAction.isLoading(true));
const getRecipes = async () => {
const response = await fetch(
*FIREBASE API*
);
const data = response.json();
return data;
};
try {
const data = await getRecipes();
console.log(data);
if (data) {
for (const key of Object.keys(data)) {
dispatch(recipeAction.replaceRecipes(data[key]));
}... other not needed code.
Redux slice
replaceRecipes(state, action: PayloadAction<Recipe>) {
const fetchedRecipe = action.payload;
state.recipes.push(fetchedRecipe);
},
【问题讨论】:
标签: reactjs typescript firebase