gpt4 book ai didi

reactjs - 我可以在 reducer 中发送一个 Action 吗?

转载 作者:行者123 更新时间:2023-12-03 12:52:16 26 4
gpt4 key购买 nike

是否可以在reducer本身中调度一个action?我有一个进度条和一个音频元素。目标是当音频元素中的时间更新时更新进度条。但我不知道在哪里放置 ontimeupdate 事件处理程序,或者如何在 ontimeupdate 的回调中调度一个操作来更新进度条。这是我的代码:

//reducer

const initialState = {
audioElement: new AudioElement('test.mp3'),
progress: 0.0
}

initialState.audioElement.audio.ontimeupdate = () => {
console.log('progress', initialState.audioElement.currentTime/initialState.audioElement.duration);
//how to dispatch 'SET_PROGRESS_VALUE' now?
};


const audio = (state=initialState, action) => {
switch(action.type){
case 'SET_PROGRESS_VALUE':
return Object.assign({}, state, {progress: action.progress});
default: return state;
}

}

export default audio;

最佳答案

在您的 reducer 完成之前启动另一个调度是一种反模式,因为当您的 reducer 完成时,您在 reducer 开始时收到的状态将不再是当前应用程序状态。但是从 reducer 内安排另一次调度并不是反模式。事实上,这就是 Elm 语言所做的事情,正如您所知,Redux 是一种将 Elm 架构引入 JavaScript 的尝试。

这是一个中间件,它将属性 asyncDispatch 添加到您的所有操作中。当您的reducer完成并返回新的应用程序状态时,asyncDispatch将触发store.dispatch,无论您执行什么操作。

// This middleware will just add the property "async dispatch" to all actions
const asyncDispatchMiddleware = store => next => action => {
let syncActivityFinished = false;
let actionQueue = [];

function flushQueue() {
actionQueue.forEach(a => store.dispatch(a)); // flush queue
actionQueue = [];
}

function asyncDispatch(asyncAction) {
actionQueue = actionQueue.concat([asyncAction]);

if (syncActivityFinished) {
flushQueue();
}
}

const actionWithAsyncDispatch =
Object.assign({}, action, { asyncDispatch });

const res = next(actionWithAsyncDispatch);

syncActivityFinished = true;
flushQueue();

return res;
};

现在你的 reducer 可以做到这一点:

function reducer(state, action) {
switch (action.type) {
case "fetch-start":
fetch('wwww.example.com')
.then(r => r.json())
.then(r => action.asyncDispatch({ type: "fetch-response", value: r }))
return state;

case "fetch-response":
return Object.assign({}, state, { whatever: action.value });;
}
}

关于reactjs - 我可以在 reducer 中发送一个 Action 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36730793/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com