gpt4 book ai didi

javascript - 了解 React-Redux 工具包语法?

转载 作者:行者123 更新时间:2023-12-05 04:29:41 25 4
gpt4 key购买 nike

我是 React、redux 的新手,很想了解我所遵循的 redux-toolkit 教程。我有如下切片。

const initialState = {
count: 0,
};

export const counterSlice = createSlice({
name: "counter",
initialState,
reducers: {
increment: (state) => {
state.count += 1;
},
},
});

export const { increment } = counterSlice.actions;

export default counterSlice.reducer;

export const incrementTest = () => (dispatch) => {
dispatch(increment());
};

然后我使用 incrementTest 操作如下

<button onClick={() => dispatch(incrementTest())}> + </button>

我想了解以下内容。

在下面的函数中

export const incrementTest = () => (dispatch) => {
dispatch(increment());
};

我们返回一个将参数作为 dispatch 参数的函数,然后使用上面定义的另一个函数 increment 的参数调用提供的 dispatch 函数,并且导出。

然而,当我们调用此函数时,我们使用 dispatch(incrementTest()) 提供 incrementTest 作为 dispatch 的参数。我不明白这个概念。我应该进一步学习 javascript 中的哪个概念来学习这个?

此外,increment reducer 将 state 作为参数(在某些情况下,action 也是如此)。谁将这个 (state,action) 提供给我们称之为 dispatch(incrementTest())

的函数

最佳答案

所以这样:

export const incrementTest = () => (dispatch) => {
dispatch(increment());
};

是一个 thunk 的例子,一个函数被调用(由 redux 中间件)有两个参数,dispatchgetState。它通常用于协调异步工作,因为您可以在函数内 await 内容或处理 promises。如果您想了解更多信息,请查找 thunk 中间件。我不确定他们为什么将此操作设为 thunk,没有必要,也许是在测试。

对于你的第二个问题,图书馆有。您所做的就是通过一个操作调用 dispatch(),库将使用当前状态和您的操作调用 reducer 函数。将其视为发出事件。您的工作是创建事件,库负责相应地更新全局状态。 reducer 是以声明方式编写的,有点。如“如果那个特定事件发生,全局状态需要如何改变?”。

关于javascript - 了解 React-Redux 工具包语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72254258/

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