Dea*_*ler 1 redux redux-toolkit
我正在阅读此页面进入react-redux https://redux.js.org/introduction/getting-started
看着有 12 行代码的基本示例(不包括用法、导入和注释),我感到非常困惑
然后我在“Redux Toolkit 示例”中读到了这一行,代码下方指出“Redux Toolkit 允许我们编写更短的逻辑,更易于阅读,同时仍然遵循相同的 Redux 行为和数据流。” 然而,这个例子有 19 行代码(不包括用法、导入和注释)
两个例子中的用法都是 3 行代码。有人可以向我解释一下吗?
也许当它扩展时,redux 工具包示例确实可以节省更多代码?老实说,我发现基本示例更容易阅读和维护。注意:我是一个完全的新手,这让我相信随着我们加大力度并雇用开发人员,基本示例可能会更好。这使他们能够更快地成长(但我只是新手中的一个数据点)
谢谢,迪恩
您对示例中的代码行的看法是正确的。也许这个简单的反例并不能充分说明 Redux Toolkit 可以节省多少代码,因为他们没有在非工具包版本中添加所有“花里胡哨”的功能。
本节称为“Redux 入门”,而不是“迁移到 Redux Toolkit”,因此我怀疑他们不想通过引入诸如操作创建器功能之类的最佳实践来压倒用户,而这并不是绝对必要的。但是您没有看到“编写更少的代码”的好处,因为您可以使用 Toolkit 删除的大多数代码都来自最初不在示例中的内容。
该函数的主要好处之一createSlice是它会自动创建动作名称常量和动作创建器函数以适应化简器中的每种情况。
此示例只是直接使用字符串名称分派原始操作store.dispatch({ type: 'counter/incremented' })。大多数开发人员不会这样做,因为它非常脆弱且不灵活。
非工具包示例的替代版本(您在大多数代码中看到的)看起来更像是这样:
// action name constants
const INCREMENTED = 'counter/incremented';
const DECREMENTED = 'counter/decremented';
// action creator functions
// usually most take some arguments
const incremented = () => ({
type: INCREMENTED,
})
const decremented = () => ({
type: DECREMENTED,
})
// reducer function
function counterReducer(state = { value: 0 }, action) {
switch (action.type) {
case INCREMENTED:
return { value: state.value + 1 }
case DECREMENTED:
return { value: state.value - 1 }
default:
return state
}
}
Run Code Online (Sandbox Code Playgroud)
如果你想包含打字稿类型,情况会变得更糟。
如果您尝试对深层嵌套数据进行不可变更新,则减速器本身可能会变得非常冗长。
以下是从这些文档复制的有关如何安全更新属性的示例state.first.second[someId].fourth
不带工具包
function updateVeryNestedField(state, action) {
return {
...state,
first: {
...state.first,
second: {
...state.first.second,
[action.someId]: {
...state.first.second[action.someId],
fourth: action.someValue
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
使用工具包:
const reducer = createReducer(initialState, {
UPDATE_ITEM: (state, action) => {
state.first.second[action.someId].fourth = action.someValue
}
})
Run Code Online (Sandbox Code Playgroud)
当您组合多个减速器时,该工具包configureStore实际上确实比 Redux 函数节省了一个步骤。createStore但这个例子再次未能表明这一点。相反,Toolkit 版本更长,因为我们设置了一个reducer属性而不是仅仅传递减速器。
典型的 Redux 应用程序使用该combineReducers实用程序将多个减速器组合为对象的属性:
import {createStore, combineReducers} from "redux";
const rootReducer = combineReducers({
counter: counterReducer,
other: otherReducer
});
const vanillaStore = createStore(rootReducer);
Run Code Online (Sandbox Code Playgroud)
使用 Toolkit,您可以直接传递您的减速器映射,而无需调用combineReducers.
import {configureStore} from "@reduxjs/toolkit";
const toolkitStore = configureStore({
reducer: {
counter: counterReducer,
other: otherReducer
}
});
Run Code Online (Sandbox Code Playgroud)
代码量大致相同。但它还包括一些默认的中间件,这些中间件在非工具包示例中将是额外的行。
| 归档时间: |
|
| 查看次数: |
294 次 |
| 最近记录: |