redux扩展工具

    科技2025-04-01  20

    redux扩展工具

    Redux is an excellent tool for managing a global state for your applications. React fits incredibly well with front-end libraries, such as React, Vue, or Angular.

    Redux是用于管理应用程序全局状态的出色工具。 React非常适合前端库,例如React,Vue或Angular。

    Redux comes with a cost, though — it’s tedious to set up and it has its fair share of boilerplate code.

    不过,Redux需要付出代价-设置起来很繁琐,并且有相当一部分样板代码。

    The redux toolkit package solves some of the pain points the Redux library has — such as writing excessive boilerplate code.

    redux工具包软件包解决了Redux库所面临的一些难题-例如编写过多的样板代码。

    redux-toolkit redux-toolkit

    The Redux Toolkit package is intended to be the standard way to write Redux logic. It was originally created to help address three common concerns about Redux.

    Redux Toolkit软件包旨在作为编写Redux逻辑的标准方法。 它最初是为了帮助解决有关Redux的三个常见问题而创建的。

    Configuring a Redux store is too complicated.

    配置Redux存储太复杂。 I have to add a lot of packages to get Redux to do anything useful.

    我必须添加很多软件包才能使Redux有用。 Redux requires too much boilerplate code.

    Redux需要太多样板代码。 redux-toolkit redux-toolkit

    入门 (Getting Started)

    The recommended way to start new apps with React and Redux Toolkit is by using the official Redux+JS template for Create React App, which takes advantage of React Redux’s integration with React components.

    建议使用React和Redux Toolkit启动新应用的方法是使用Create React App的官方Redux + JS模板,该模板利用了React Redux与React组件的集成。

    npx create-react-app my-react-redux-app --template redux http://localhost:3000/ http:// localhost:3000 /上运行的Redux应用程序

    标准商店设置(Standard Store Setup)

    The example below is from the Configuring Your Store page. The Redux documentation shows a typical store setup process.

    下面的示例来自“配置商店”页面。 Redux文档显示了典型的商店设置过程。

    import { applyMiddleware, createStore } from 'redux' import { composeWithDevTools } from 'redux-devtools-extension' import thunkMiddleware from 'redux-thunk' import monitorReducersEnhancer from './enhancers/monitorReducers' import loggerMiddleware from './middleware/logger' import rootReducer from './reducers' export default function configureStore(preloadedState) { const middlewares = [loggerMiddleware, thunkMiddleware] const middlewareEnhancer = applyMiddleware(...middlewares) const enhancers = [middlewareEnhancer, monitorReducersEnhancer] const composedEnhancers = composeWithDevTools(...enhancers) const store = createStore(rootReducer, preloadedState, composedEnhancers) if (process.env.NODE_ENV !== 'production' && module.hot) { module.hot.accept('./reducers', () => store.replaceReducer(rootReducer)) } return store }

    This example above is verbose and isn’t always straightforward. The Redux createStore function takes positional arguments: (rootReducer, preloadedState, enhancer)— it's easy to forget which parameter is which.

    上面的例子很冗长,并不总是那么简单。 Redux createStore函数采用位置参数: (rootReducer, preloadedState, enhancer) —很容易忘记哪个参数是哪个。

    The process of setting up middleware and enhancers can be confusing, especially if you’re trying to add several pieces of configuration.

    设置中间件和增强器的过程可能会令人困惑,尤其是在您尝试添加多个配置的情况下。

    The Redux DevTools Extension documentation initially suggests using some hand-written code that checks the global namespace to see if the extension is available. The problem with that is many developers copy and paste those snippets — which makes the setup code harder to read overall.

    Redux DevTools Extension文档最初建议使用一些手写代码来检查全局名称空间,以查看扩展是否可用。 这样做的问题是,许多开发人员复制并粘贴了这些代码片段,这使安装代码难以整体阅读。

    使用redux-kit简化商店设置 (Simplifying Store Setup With redux-kit)

    Instead of writing our own store, let’s use the baked in version from the redux-kit library. Below is an example of how you can import and use the configureStore function.

    不用编写我们自己的商店,而是使用redux-kit库中的烘焙版本。 以下是如何导入和使用configureStore函数的示例。

    import { configureStore } from '@reduxjs/toolkit' import rootReducer from './reducers' const store = configureStore({ reducer: rootReducer }) export default store

    The simplest way to use configureStore is to just pass the root reducer function as a parameter named reducer.

    使用configureStore的最简单方法是只将根reducer函数作为名为reducer的参数传递。

    In addition, configureStore adds some middleware by default, each with a specific goal:

    另外, configureStore默认添加一些中间件,每个中间件都有特定的目标:

    redux-thunk is the most commonly used middleware for working with both synchronous and async logic outside of components

    redux-thunk是用于组件外部同步和异步逻辑的最常用中间件

    In development, middleware that check for common mistakes like mutating the state or using non-serializable values.

    在开发中,这种中间件检查常见错误,例如改变状态或使用不可序列化的值。

    configureStore可帮助以下方面 (configureStore helps with the following)

    Having the options object with “named” parameters, which is easier to read.

    使options对象带有“命名”参数,这更易于阅读。Letting you provide arrays of middleware and enhancers you want to add to the store.

    让您提供要添加到商店的中间件和增强器的数组。

    Calling applyMiddleware and compose for you.

    调用applyMiddleware并为您compose 。

    Enabling the Redux DevTools Extension out of the box.

    开箱即用地启用Redux DevTools Extension。

    The store setup code itself is a lot shorter and easier to read. It also provides you with great functionality out of the box.

    商店设置代码本身更短并且更易于阅读。 它也为您提供了强大的功能。

    自定义商店设置 (Customize the Store Setup)

    In case you need to customize the store setup — you can pass additional options.

    如果需要自定义商店设置,则可以传递其他选项。

    Here’s what the hot reloading example might look like using Redux Toolkit.

    这是使用Redux Toolkit的热重载示例的外观。

    import { configureStore, getDefaultMiddleware } from '@reduxjs/toolkit' import monitorReducersEnhancer from './enhancers/monitorReducers' import loggerMiddleware from './middleware/logger' import rootReducer from './reducers' export default function configureAppStore(preloadedState) { const store = configureStore({ reducer: rootReducer, middleware: [loggerMiddleware, ...getDefaultMiddleware()], preloadedState, enhancers: [monitorReducersEnhancer] }) if (process.env.NODE_ENV !== 'production' && module.hot) { module.hot.accept('./reducers', () => store.replaceReducer(rootReducer)) } return store }

    If you provide the middleware argument, configureStore will only use whatever middleware you've listed.

    如果您提供middleware参数,则configureStore将仅使用您列出的任何中间件。

    If you want to have some custom middleware and the defaults bundled together — you can call getDefaultMiddleware and include the results in the middleware array you provide.

    如果您希望将某些自定义中间件和默认值捆绑在一起,则可以调用getDefaultMiddleware并将结果包括在您提供的middleware数组中。

    使用createReducer简化减速器 (Simplifying Reducers With createReducer)

    Redux Toolkit includes a createReducer function similar to the one shown in the Redux docs. However, our createReducer utility has some special "magic" that makes it even better.

    Redux Toolkit包含一个createReducer函数,类似于Redux文档中所示的函数。 但是,我们的createReducer实用程序具有一些特殊的“魔术”,使其变得更好。

    It uses the Immer library internally, which lets you write code that "mutates" some data, but actually applies the updates immutably. This makes it effectively impossible to accidentally mutate state in a reducer.

    它在内部使用Immer库,该库使您可以编写使某些数据“突变”但实际上不可变地应用更新的代码。 这实际上使得不可能意外地改变减速器中的状态。

    import { createReducer } from '@reduxjs/toolkit' const todosReducer = createReducer([], { ADD_TODO: (state, action) => { // "mutate" the array by calling push() state.push(action.payload) }, TOGGLE_TODO: (state, action) => { const todo = state[action.payload.index] // "mutate" the object by overwriting a field todo.completed = !todo.completed }, REMOVE_TODO: (state, action) => { // Can still return an immutably-updated value if we want to return state.filter((todo, i) => i !== action.payload.index) } }) export default todosReducer;

    使用createReducer Function注意事项(Considerations for Using the createReducer Function)

    While the Redux Toolkit createReducer function is helpful, keep this in mind:

    虽然Redux Toolkit createReducer函数很有用,但请记住以下createReducer :

    The “mutative” code only works correctly inside of our createReducer function.

    “可变”代码仅在我们的createReducer函数内部正常工作。

    Immer won’t let you mix “mutating” the draft state and also returning a new state value.

    Immer不允许您混合“改变”草稿状态并返回新的状态值。

    See the createReducer API reference for more details.

    有关更多详细信息,请参见createReducer API参考。

    使用createAction定义动作创建者 (Defining Action Creators With createAction)

    Writing action creators by hand will get tedious and introduces a lot of boilerplate code.

    手工编写动作创建者会很乏味,并介绍了许多样板代码。

    Redux Toolkit provides a function called createAction, which simply generates an action creator that uses the given action type and turns its argument into the payload field.

    Redux Toolkit提供了一个名为createAction的函数,该函数仅生成一个使用给定操作类型的操作创建者,并将其参数转换为payload字段。

    import { createAction } from '@reduxjs/toolkit' const addTodo = createAction('ADD_TODO') export default addTodo; // Usage addTodo({ text: 'Buy milk' }) // {type : "ADD_TODO", payload : {text : "Buy milk"}})

    createAction also accepts a "prepare callback" argument, which allows you to customize the resulting payload field and optionally add a meta field.

    createAction还接受“ prepare callback”参数,该参数允许您自定义生成的payload字段并选择添加meta字段。

    See the createAction API reference for details on defining action creators with a prepare callback.

    有关使用prepare回调定义动作创建者的详细信息,请参见createAction API参考。

    If you’re feeling curious, check out the official documentation for an in-depth dive.

    如果您感到好奇,请查看官方文档以进行深入的了解。

    结论 (Conclusion)

    Thanks for reading — hope you find the newer approach handy. Happy coding!

    感谢您的阅读-希望您能找到方便的新方法。 编码愉快!

    翻译自: https://medium.com/better-programming/boost-your-productivity-with-the-redux-toolkit-7a14657351c3

    redux扩展工具

    相关资源:jdk-8u281-windows-x64.exe
    Processed: 0.010, SQL: 8