Redux Store 不使用在 firebase 实时数据库上创建的数据更新状态

Redux Store does not update state with created data on firebase real-time database

我已经设置了我的 firebase 函数并且它运行良好。我的应用程序的数据流是这样的:

  1. 用户填写表格并提交{作品}
  2. 数据发送到实时数据库{works}
  3. 然后通过监听数据库引用将数据传回 redux 存储。 {不起作用}
  4. 然后数据显示在 table true redux 存储中,供用户查看 his/her 提交的信息。 {不起作用,因为 3 不起作用}

我遇到问题的地方是 3。

这是我的 Redux 操作文件:

import {
  SAVE_FORM,
  UPDATE_STORE
} from "./types";

export const saveForm = user => {
  return {
    type: SAVE_FORM,
    payload: user
  };
};

export const updateStore = data => {
  return {
    type: UPDATE_STORE,
    payload: data
  };
};

这是我的减速器:

import {
  SAVE_FORM,
  UPDATE_STORE
} from "../actions/types";

const initialState = {
  users: [],
  db: ""
};

export default function (state = initialState, action) {
  switch (action.type) {
    case SAVE_FORM:
      return {
        ...state,
        users: [action.payload]
      };

    case UPDATE_STORE:
      return {
        db: [action.payload]
      };
    default:
      return state;
  }
}

最后是我的 sagas 文件:

import {
  database
} from "./firebase-config"
import axios from "axios"
import {
  put,
  fork,
  takeEvery,
  take
} from 'redux-saga/effects'
import {
  eventChannel
} from "redux-saga"
import {
  SAVE_FORM,
  UPDATE_STORE
} from "./actions/types"

export function* sendRequest({
  payload
}) {
  //console.log(payload);
  yield axios.post('https://dummy.com/user', payload)
    .then(res => {
      // here will be code
      console.log(res)
    })
    .catch(error => {
      console.log(error);
    });
};

export function* watchSendAction() {
  yield takeEvery(SAVE_FORM, sendRequest);
}

function createEventChannel() {
  const listener = eventChannel(emit => {
    database.ref('entries/users').on('value', data => emit(data.val()));
    return () => database.ref('entries/users').off(listener);
  });
  return listener;
}

//This is supposed to update my store with the data received by the database
function* startListener() {
  const updateChannel = createEventChannel();
  while (true) {
    const data = yield takeEvery(updateChannel);
    yield put(UPDATE_STORE(data));
  }
}


export default function* helloSaga() {
  yield fork(watchSendAction);
  yield fork(startListener);
}

我似乎无法弄清楚我做错了什么。

我怀疑问题出在您的 startListener 故事中。您应该使用带有 take 效果的 while 循环,或者使用没有 while 循环的 takeEvery。现在您正在将两者混合在一起。

试试这个:

function* startListener() {
  const updateChannel = createEventChannel();
  while (true) {
    const data = yield take(updateChannel);
    yield put(UPDATE_STORE(data));
  }
}

或者这个:

function* startListener() {
  const updateChannel = createEventChannel();
  yield takeEvery(updateChannel, function*(data) {
    yield put(UPDATE_STORE(data));
  });
}