【问题标题】:Redux toolkit action is somehow not syncRedux 工具包操作不知何故不同步
【发布时间】:2021-11-30 22:54:14
【问题描述】:

我正在使用 redux 工具包 createSlice:

export const counter = createSlice({
  ...
  reducers: {
    increment: (state, action) => state + 1,
    ...
  }
});

export const { increment } = counter.actions;

在组件中使用:

import React, { useEffect } from "react";
import { connect } from "react-redux";
import { increment as _increment } from "../slices/counter";

const Counter = ({ counter, increment }) => {
  useEffect(() => {
    console.log(counter); // Let's assume that counter=k
    increment();
    console.log(counter); // I think that here counter should be equal k+1, but it still is k as if increment is async
  }, []);
  return <div>Counter: {counter}</div>;
};

const mapStateToProps = (state) => ({
  counter: state.counter
});

const mapDispatchToProps = {
  increment: _increment
};

export default connect(mapStateToProps, mapDispatchToProps)(Counter);

我希望增量函数是同步的,以便在执行它后的下一行 redux 存储将被更改。在我的示例中,我希望第一个 console.log 返回 k 和第二个 k+1。为什么会发生这种情况。有没有办法等到商店发生变化?

这里是sandbox

【问题讨论】:

标签: reactjs redux redux-toolkit


【解决方案1】:

它工作正常,我添加了一个按钮来调用 increment() 方法,一旦点击,我想你认为它不起作用,因为 useEffect 方法中存在对 increment 方法的调用,一旦组件加载“无依赖关系”就会触发"

对于您的沙箱,尝试更改代码中的内容以重新渲染 Counter 组件,您将看到计数器递增

Your SandBox Fork

【讨论】:

    猜你喜欢
    • 2022-12-11
    • 1970-01-01
    • 2019-02-03
    • 2021-12-05
    • 2020-09-17
    • 2021-12-08
    • 2017-12-28
    • 1970-01-01
    • 2020-07-30
    相关资源
    最近更新 更多