javascript - 从 Firebase 获取数据时,来自 Redux Toolkit 的 createAsyncThunk 会产生未定义的有效负载
问题描述
从存储在集合中的 Google Firebase 获取笔记数据时,我正在使用createAsyncThunk
来自 Redux Toolkit 的 APInotes
在notebookSlice.js
我定义了功能 thunk 和 slice
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
const firebase = require('firebase');
export const fetchNotes = createAsyncThunk(
'users/fetchNotes',
async () => {
firebase.firestore().collection('notes').get()
.then((snapshot) => {
var data = [];
snapshot.forEach((doc) => {
data.push({
title: doc.data().title,
body: doc.data().body,
id: doc.id
})
});
console.log(data); // not null
return data;
})
.catch((err) => {
console.log(err)
});
}
)
export const notebookSlice = createSlice({
name: 'notebook',
initialState: {
selectedNoteIndex: null,
selectedNote: null,
notes: null,
count: 3,
loadingNotes: false,
error: null
},
reducers: {
...
},
extraReducers: {
[fetchNotes.pending]: (state, action) => {
if (state.loadingNotes === false) {
state.loadingNotes = true
}
},
[fetchNotes.fulfilled]: (state, action) => {
if (state.loadingNotes === true) {
state.notes = action.payload;
console.log(action.payload); // null
state.loadingNotes = false;
}
},
[fetchNotes.rejected]: (state, action) => {
if (state.loadingNotes === true) {
state.loadingNotes = false;
state.error = action.payload;
}
}
}
我在组件中使用它们sidebar.js
import React, {useState, useEffect} from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { fetchNotes } from './notebookSlice';
export function Sidebar(props) {
const dispatch = useDispatch();
useEffect(() => {
dispatch(fetchNotes());
})
return (
...
)
}
我很确定我从 thunk 函数中获得了完整的数据,但state.notes
在获取具有最终fulfilled
状态的数据后仍然为空。我的代码有什么问题?
解决方案
在fetchNotes
中,您声明了一个承诺,但没有从函数本身返回任何值,所以基本上它是一个 javascript 问题,与 Redux/React 无关。
export const fetchNotes = createAsyncThunk("users/fetchNotes", async () => {
// Returns data after resolve
const data = await firebasePromise();
return data;
});
您当前的代码返回一个承诺,您需要在某个时候解决它。
export const fetchNotes = createAsyncThunk("users/fetchNotes", async () => {
const promise = firebase
.firestore()
.collection("notes")
.get()
.then((snapshot) => {
const data = [];
// assign data
return data;
});
const data = await promise;
return data;
});
//
阅读MDN 文档中有关 Promise 的更多信息。
推荐阅读
- realm - 升级到最新的领域版本 5.0 后在 swift 中写入双精度时领域崩溃
- python - 如何使循环从索引 150 开始并从列表中打印 20 个值?
- javascript - 如何将一组数字分类到均匀分布的桶中?
- ios - 裁剪 CIImage 会导致图像过宽 1px
- java - 从 1 个数组列表中删除对象并添加到另一个
- javascript - 使用任意字符串查询表
- asp.net-mvc - 了解加载 ChildAction 的过程
- mysql - 在 for 循环 MySQL Node.js 内切换数据库,它的切换速度不够快/它们重叠?
- arrays - Swift:可以发现数组中元素的类型并用于指定泛型类型参数吗?
- mysql - MYSQL查询中的重复列值