jan*_*ann 15 javascript reactjs redux redux-saga
我正在将Pusher实现到我的React + Redux Saga应用程序中,但是我遇到了一些问题,我在一些回调中遇不到这些put(...)方法.console.log(...)在方法中使用等确实显示,但我无法进入put我的应用程序状态.
我在异步/生成器函数的一些实现上可能是错的,但我现在几乎被卡住了.
我的代码说明了什么不会触发:
import { takeLatest } from 'redux-saga'
import { call, put } from 'redux-saga/effects'
// Pusher actions
export const pusherConnecting = () => {
return {
type: ActionTypes.PUSHER_CONNECTING
}
};
export const pusherConnectSucceeded = (client) => {
return {
type: ActionTypes.PUSHER_CONNECT_SUCCEEDED,
client: client
}
};
const pusherConnectFailed = (exception) => {
return {
type: ActionTypes.PUSHER_CONNECT_FAILED,
message: exception
}
};
// Pusher Saga
function * connectPusher(action) {
try {
const pusher = yield call(Api.connectPusher, action.directory, function(subscription) {
subscription.bind(PUSHER_BIND_RELOAD, function() {
location.reload(true);
});
subscription.bind(PUSHER_BIND_REQUEST_DATA, function(data) {
if (data) {
put(updateDirectory(data));
} else {
put(requestDirectory(action.directory.id));
}
});
});
pusher.connection.bind('connected', function() {
put(pusherConnectSucceeded(pusher));
});
yield put(pusherConnecting());
} catch (e) {
yield put(pusherConnectFailed(e));
}
}
export default function * pusherSaga() {
yield * takeLatest(ActionTypes.DIRECTORY_FETCH_SUCCEEDED, connectPusher);
}
// My Api.ConnectPusher
export function * connectPusher(directory, subscription) {
var pusher = new Pusher(PUSHER_KEY, {
encrypted: true
});
var channels = ["test1", "test2" ];
for (var i = 0; i < channels.length; i++) {
// Take each channel and callback with the subscription
yield subscription(pusher.subscribe(channels[i]));
}
return pusher;
}
Run Code Online (Sandbox Code Playgroud)
基于@Sebastien的解决方案
yield put(yield onConnect(pusher));
function onConnect(pusher) {
return new Promise((resolve, reject) => {
pusher.connection.bind('connected', function() {
resolve(pusherConnectSucceeded(pusher));
});
});
}
Run Code Online (Sandbox Code Playgroud)
Redux-saga不允许put不使用关键字yield.put创建了一个必须被解释/执行的简单json对象/效果,如果你不屈服则不会.
此外,即使使用yield put(...),如果这是在回调中完成的,也不会被解释,因为Redux-saga没有能力在其解释器中运行回调.它们只是作为正常的回调运行,什么都不会发生.
如果subscription.bind应该返回单个结果,则可以将该调用包装为返回promise的函数,然后生成该promise.
如果subscription.bind应该返回结果流,则可能需要而不是创建通道.我想将来有人会发布一些可以轻松允许将Observable转换为Redux-saga流的东西
请注意,如果您不需要多次取消订阅/重新订阅,那么将此代码置于传奇之外可能更为简单,只需执行此操作
subscription.bind(PUSHER_BIND_RELOAD, function() {
location.reload(true);
});
subscription.bind(PUSHER_BIND_REQUEST_DATA, function(data) {
if (data) {
reduxStore.dispatch(updateDirectory(data));
} else {
reduxStore.dispatch((requestDirectory(action.directory.id));
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2002 次 |
| 最近记录: |