繁体   English   中英

那么...... Redux 动作调度是同步还是异步? (没有 thunk 或 saga)

[英]So… Redux action dispatch is sync or async? (Without thunk or saga)

当我调度redux动作时,我对行为有点困惑。

例子:

onPressAdd() {
    this.props.addFloor({
        name: this.state.floor_name,
    });
    console.log(this.props.floors);
}

我正在调用 redux 操作addFloor什么将地板添加到存储中的数组中,然后我 console.log 这个变量,我期待更新 state ( [{name:'whatever'}] )但我得到[] (空数组)

示例 2:

async onPressAdd() {
    await this.props.addFloor({
        name: this.state.floor_name,
    });
    console.log(this.props.floors);
}

在这个例子中,我得到了完美的更新商店: [{name:'whatever'}]

我到处读到“如果没有 thunk 或 saga,Redux 动作调度是同步的(直接方式:调度动作->减少->存储”,但 rhis 证明调度是异步的。

那么真相在哪里?

调度本身是 100% 同步的。

这是 Redux 存储的微小实现:

function createStore(reducer) {
    var state;
    var listeners = []

    function getState() {
        return state
    }

    function subscribe(listener) {
        listeners.push(listener)
        return function unsubscribe() {
            var index = listeners.indexOf(listener)
            listeners.splice(index, 1)
        }
    }

    function dispatch(action) {
        state = reducer(state, action)
        listeners.forEach(listener => listener())
    }

    dispatch({})

    return { dispatch, subscribe, getState }
}

dispatch()返回时,store 已经执行了你的 reducer function,并调用了所有的 store 订阅者回调。

只有当您开始将中间件添加到 store 中时,调度过程才能被中断,因为任何中间件都可以延迟、停止或重写任何已调度的操作。

您在该示例中看到的内容实际上是基于 React 的工作原理。 在那个点击处理程序内部,React 还没有重新渲染和更新组件的 props,所以this.props.whatever在调度之前和之后仍然是相同的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM