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

Bat*_*rka 6 flux reactjs redux

当我派遣行动时,我对行为有点困惑redux

例子:

onPressAdd() {
    this.props.addFloor({
        name: this.state.floor_name,
    });
    console.log(this.props.floors);
}
Run Code Online (Sandbox Code Playgroud)

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

示例2:

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

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

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

那么真理在哪里呢?

mar*_*son 8

调度本身是 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 }
}
Run Code Online (Sandbox Code Playgroud)

dispatch()返回时,商店已经执行了您的减速器函数,并调用了所有商店订阅者回调。

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

您在该示例中看到的实际上是基于 React 的工作原理。在该单击处理程序内部,React 尚未重新渲染和更新组件的 props,因此this.props.whatever在分派之前和之后仍然相同。