gpt4 book ai didi

redux - Redux 教程示例中如何生成 counterReducer

转载 作者:行者123 更新时间:2023-12-05 01:09:59 25 4
gpt4 key购买 nike

我正在阅读 Redux 官方教程。当我看到在任何模块中都没有的 counterReducer 有值(value)并且有效时,我感到很惊讶!我找不到它的任何描述,但是:

Since we know that the counterReducer function is coming fromfeatures/counter/counterSlice.js, let's see what's in that file, pieceby piece.

我什至将 slicer 的名称更改为 counter3,但它仍然有效!

谁能告诉我它是如何生成的?

counterSlice.js

import { createSlice } from '@reduxjs/toolkit';
export const counterSlice = createSlice({
name: 'counter3',
initialState: {
value: 0,
},
reducers: {
increment: state => {
state.value += 1;
},
decrement: state => {
state.value -= 1;
},
incrementByAmount: (state, action) => {
state.value += action.payload;
},
},
});

export const { increment, decrement, incrementByAmount } = counterSlice.actions;

export const incrementAsync = amount => dispatch => {
setTimeout(() => {
dispatch(incrementByAmount(amount));
}, 1000);
};

export const selectCount = state => state.counter.value;

export default counterSlice.reducer;

store.js(我们在 store.js 模块中使用)

import { configureStore } from '@reduxjs/toolkit';
import counterReducer from '../features/counter/counterSlice'; //HERE IS THE IMPORTING PLACE

export default configureStore({
reducer: {
counter: counterReducer,
},
});

https://redux.js.org/tutorials/essentials/part-2-app-structure#creating-slice-reducers-and-actions

最佳答案

counterSlice.js 使用 ES6 “默认导出”来导出 createSlice 生成的 reducer 函数:

export default counterSlice.reducer;

然后任何其他文件都可以使用“默认导入”来获取对该 reducer 函数的引用。但是,当我们默认导入一个值时,我们可以给它任何我们想要的名称:

// fileA.js
import counterReducer from "./features/counter/counterSlice"

// fileB.js
import someReducer from "./features/counter/counterSlice"

// fileC.js
import fred from "./features/counter/counterSlice"

所有这三个变量都将指向同一个 reducer 函数 - 这只是我们创建的局部变量名称是什么的问题。

因此,在这种情况下,store.js 中的 counterReducer 变量是对从 counterSlice.js 文件。

关于redux - Redux 教程示例中如何生成 counterReducer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64594063/

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