javascript - 从 Firebase 获取数据时,来自 Redux Toolkit 的 createAsyncThunk 会产生未定义的负载

标签 javascript reactjs redux promise redux-toolkit

我正在使用 Redux Toolkit 中的 createAsyncThunk API 从存储在 notes 集合中的 Google Firebase 获取笔记数据

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 中,您声明了一个 promise 但没有从函数本身返回任何值,所以基本上它是一个 javascript 问题,与 Redux/React 无关。

export const fetchNotes = createAsyncThunk("users/fetchNotes", async () => {
  // Returns data after resolve
  const data = await firebasePromise();
  return data;
});

您当前的代码返回一个 promise ,您需要在某个时候解决它。

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;
});

// 

阅读更多关于 promises in MDN docs 的信息.

关于javascript - 从 Firebase 获取数据时,来自 Redux Toolkit 的 createAsyncThunk 会产生未定义的负载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62358759/

相关文章:

reactjs - 将 react 脚本升级到 4.x.x 破坏了我的应用程序

javascript - React Native with react-navigation and Redux - 如何实现全局可用的 'Sign Out' 按钮

javascript - Raphael/SVG 路径定义总是以 'M' 开头吗? (如果不是,这样的路径的原点总是 0,0 吗?)

javascript,访问存储在变量中的 json 键

javascript - Java/JavaScript - java.time.Instant 序列化到 javascript Date

react-native - 如何以及在何处使用 AsyncStorage 保存整个 redux 存储

reactjs - 为什么我们不能仅将 GraphQL 与 Redux 结合使用

javascript - 使用 JavaScript 确定一个月中的天数的最佳方法是什么?

javascript - setTimeout后异步回调执行问题

reactjs - 在React-Select中获取选择的值