我已经设置了我的Firebase函数,并且可以正常运行。我的应用程序的数据流如下:
我遇到问题的地方是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循环,或者takeEvery
不使用while循环。现在,您正在将两者混合在一起。
尝试这个:
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));
});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句