【发布时间】: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
【问题讨论】:
-
这能回答你的问题吗? stackoverflow.com/questions/54069253/…
标签: reactjs redux redux-toolkit