Redux – A predictable state container for JavaScript applications

Redux – A predictable state container for JavaScript applications

2022-10-10 0 887
Resource Number 44985 Last Updated 2025-02-24
¥ 0USD Upgrade VIP
Download Now Matters needing attention
Can't download? Please contact customer service to submit a link error!
Value-added Service: Installation Guide Environment Configuration Secondary Development Template Modification Source Code Installation

Redux is a predictable state container for JavaScript applications.

Redux – A predictable state container for JavaScript applications插图

Redux It helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test. Most importantly, it provides a great developer experience, such as real-time code editing combined with a time travel debugger. You can use Redux with React or any other visual library. It’s small (2kB, including dependencies), but there’s a huge plugin ecosystem available.

The Redux Toolkit is our official recommended way to write Redux logic. It revolves around the Redux core and contains packages and features that we feel are critical to building Redux applications. The Redux Toolkit is built on our suggested best practices, simplifying most Redux tasks, preventing common errors, and making writing Redux applications easier.

Core concepts

Imagine that the state of your application is described as a plain object. For example, the state of a todo app might look like this:

{
  todos: [{
    text: 'Eat food',
    completed: true
  }, {
    text: 'Exercise',
    completed: false
  }],
  visibilityFilter: 'SHOW_COMPLETED'
}

This object is like a “model” except without a setter. This is so that different parts of the code can’t change state at will, leading to hard-to-reproduce errors.

To change something in the state, you need to schedule an action. The action is a simple JavaScript object (note that we didn’t introduce any magic?). It describes what happened. Here are some examples:

{ type: 'ADD_TODO', text: 'Go to swimming pool' }
{ type: 'TOGGLE_TODO', index: 1 }
{ type: 'SET_VISIBILITY_FILTER', filter: 'SHOW_ALL' }

Forcing each change to be described as an operation gives us a clear picture of what is happening in our application. If something changes, we know why it changed. Actions are like crumbs of what has already happened. Finally, to tie the states and actions together, we wrote a function called reducer. Again, there’s nothing magical about it – it’s just a function that takes a state and an action as arguments and returns the next state of the app. Writing such a function for a large application would be difficult, so let’s write smaller functions to manage part of the state:

function visibilityFilter(state = 'SHOW_ALL', action) {
  if (action.type === 'SET_VISIBILITY_FILTER') {
    return action.filter
  } else {
    return state
  }
}

function todos(state = [], action) {
  switch (action.type) {
    case 'ADD_TODO':
      return state.concat([{ text: action.text, completed: false }])
    case 'TOGGLE_TODO':
      return state.map((todo, index) =>
        action.index === index
          ? { text: todo.text, completed: !todo.completed }
          : todo
      )
    default:
      return state
  }
}

We wrote another reducer to manage the full state of our application by calling both reducers to get the corresponding state keys:

function todoApp(state = {}, action) {
  return {
    todos: todos(state.todos, action),
    visibilityFilter: visibilityFilter(state.visibilityFilter, action)
  }
}

This is basically the whole idea of Redux. Note that we’re not using any Redux API. It comes with some utilities to facilitate this pattern, but the main idea is that you describe how your state updates over time in response to action objects, and 90% of the code you write is just plain JavaScript, without using Redux itself, its API, or any magic.

Install Redux

The Redux Toolkit includes the Redux core, And other key packages (such as Redux Thunk and Reselect) that we feel are critical for building Redux apps.
This can be used with module bundlers or Node applications as a package on NPM:

# NPM
npm install @reduxjs/toolkit

# Yarn
yarn add @reduxjs/toolkit

It can also be used as a UMD build, This can be loaded from the dist folder of the on unpkg. UMD builds make Redux Toolkit available as window.RTK global variables.

Redux

# NPM
npm install redux

# Yarn
yarn add redux

You’ll also need React bindings and developer tools class=”data-color–tt-darkmode-bec1c7″>.

npm install react-redux
npm install --save-dev @redux-devtools/core

Note that unlike Redux itself, many packages in the Redux ecosystem don’t provide UMD builds, We recommend using Webpack and Browserify CommonJS module bundling for the most comfortable development experience.

Create a React Redux

The recommended way to start a new app with React and Redux is to use official Redux+JS or Redux+TS template Create React App, Redux Toolkit and React Redux integration with React components.

# Redux + Plain JS template
npx create-react-app my-app --template redux

# Redux + TypeScript template
npx create-react-app my-app --template redux-typescript

Configure your store

First, let’s look at index.js where we created the store:

import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import rootReducer from './reducers'
import App from './components/App'

const store = createStore(rootReducer)

render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
)

In this code, we pass the reducer to the ReduxcreateStore function, The function returns a store object. We then pass this object to the react-redux Provider component, which is rendered at the top of the component tree.

This ensures that whenever we connect to Redux in our application, react-redux connect The store is available to all our components.

Extending Redux

Most apps extend the functionality of their Redux storage by adding middleware or storage enhancers Middleware adds additional dispatch functionality to Redux functions. Enhancers add additional functionality to Redux storage.

We’ll add two middleware and an enhancer:

  • redux-thunk middleware, which allows easy asynchronous use of scheduling.
  • A middleware that records dispatched actions and new states produced.
  • An enhancer that records the time it takes the reducer to process each action.
npm install  redux-thunk

middleware

const logger = store => next => action => {
  console.group(action.type)
  console.info('dispatching', action)
  let result = next(action)
  console.log('next state', store.getState())
  console.groupEnd()
  return result
}

export default logger

enhancer

const round = number => Math.round(number * 100) / 100

const monitorReducerEnhancer =
  createStore => (reducer, initialState, enhancer) => {
    const monitoredReducer = (state, action) => {
      const start = performance.now()
      const newState = reducer(state, action)
      const end = performance.now()
      const diff = round(end - start)

      console.log('reducer process time:', diff)

      return newState
    }

    return createStore(monitoredReducer, initialState, enhancer)
  }

export default monitorReducerEnhancer

Let’s add these to our existing index.js.

    • First, We’ll need importredux-thunk plus our loggerMiddlewareand monitorReducerEnhancer, plus two extra functions that Redux provides: applyMiddlewareand compose.
    • Then we create a store enhancer using applyMiddleware, It takes our loggerMiddleware and applies thunkMiddleware to the store’s dispatch function.

< li > < span class = “data – color – tt – darkmode – bec1c7” > next, we’ll composenewmiddlewareEnhancer and our portfolio monitorReducerEnhancer into a function.

  • This is required because you can only pass one enhancer to createStore. To use multiple enhancers, you must first combine them into one larger enhancer, as shown in this example.
  • Finally, we pass the new composedEnhancers function createStore as its third argument. Note: The second parameter we’ll ignore allows you to preload the state into storage.

 

import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { applyMiddleware, createStore, compose } from 'redux'
import thunkMiddleware from 'redux-thunk'
import rootReducer from './reducers'
import loggerMiddleware from './middleware/logger'
import monitorReducerEnhancer from './enhancers/monitorReducer'
import App from './components/App'

const middlewareEnhancer = applyMiddleware(loggerMiddleware, thunkMiddleware)
const composedEnhancers = compose(middlewareEnhancer, monitorReducerEnhancer)

const store = createStore(rootReducer, undefined, composedEnhancers)

render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
)

Learning resources

The Redux documentation is designed to teach the basic concepts of Redux and explain key concepts that are used in real-world applications. However, documentation does not cover everything. Happily, there are many other great resources available for learning Redux. We encourage you to check them out. Many of these cover topics that are out of the scope of the documentation or describe the same topics in other ways that might be better suited to your learning style.

Introduction to React, Redux, and Typescript: A set of slides by Redux maintainer Mark Erikson, covering the basics of React, Redux, and TypeScript. Redux topics include store, reducers, middleware, React-Redux, and Redux Toolkit.

https://blog.isquaredsoftware.com/2020/12/presentations-react-redux-ts-intro/

Redux tutorial: Overview and walkthrough: Well written tutorial by Tania Rascia that quickly explains the key concepts of Redux, And shows how to compose a basic Redux + React app using vanilla Redux and the Redux Toolkit.

https://www.taniarascia.com/redux-react-guide/

Redux beginner – a brain-friendly guide to learning Redux: Build a small todo app with the Redux Toolkit and React-Redux, including data fetch-ing.

https://www.freecodecamp.org/news/redux-for-beginners-the-brain-friendly-guide-to-redux/</ p>

Make Redux easy with the Redux Toolkit and Typescript: A helpful tutorial on how to use Redux Toolkit and TypeScript together to write Redux applications, And how RTK simplifies typical Redux usage.

https://www.mattbutton.com/redux-made-easy-with-redux-toolkit-and-typescript/

Basic example

The application’s entire global state is stored in a single storeaction, an object that describes what’s happening, < span>< span class=”data-color–tt-darkmode-b3bbc5″> store. To specify how the state should be updated in response to an action, You write pure reducer function to calculate the new state based on the old state and the operation.

import { createStore } from 'redux'

/**
* This is a reducer - a function that takes the current state value and an action object describing "what happened", and returns a new state value.
* The signature of the reducer is: (state, action) => newState
*
* Redux state should only contain plain JS objects, arrays, and primitives.
* The root state value is usually an object. The important thing is that you shouldn't mutate the state object, but instead return a new object when the state changes.
*
* You can use any conditional logic you want in the reducer. In this example,
* We use a switch statement, but it's not required.
 */
function counterReducer(state = { value: 0 }, action) {
  switch (action.type) {
    case 'counter/incremented':
      return { value: state.value + 1 }
    case 'counter/decremented':
      return { value: state.value - 1 }
    default:
      return state
  }
}

// Create a Redux store to hold your app's state. 
// Its API is {subscribe, dispatch, getState}. 
let store = createStore(counterReducer)

// You can use subscribe() to update the UI in response to state changes. 
// Usually you'd use a view-binding library (like React Redux) instead of subscribing () directly. 
// There may be other use cases that would be helpful for subscriptions as well. 

store.subscribe(() =>  console.log(store.getState()))

// The only way to change internal state is to schedule an action. 
// These actions can be serialized, logged, or stored, and then replayed. 
store.dispatch({ type: 'counter/incremented' })
// {value: 1}
store.dispatch({ type: 'counter/incremented' })
// {value: 2}
store.dispatch({ type: 'counter/decremented' })
// {value: 1}

You don’t need to change the state directly, Instead, you specify the changes to occur using a plain object called actions. Then you write one called reducer to determine how each action transforms the state of the entire application.

Redux toolkit examples

The Redux Toolkit simplifies writing Redux logic and setting up stores. Using the Redux Toolkit, the same logic looks like this:

import { createSlice, configureStore } from '@reduxjs/toolkit'

const counterSlice = createSlice({
  name: 'counter',
  initialState: {
    value: 0
  },
  reducers: {
    incremented: state => {
      //The Redux Toolkit allows us to write "mutation" logic in our reducers. it
      // Without actually mutating the state, because it uses Immer,
      // It detects changes in the "draft state" and generates a brand new one based on those changes
      // Immutable state
      state.value += 1
    },
    decremented: state => {
      state.value -= 1
    }
  }
})

export const { incremented, decremented } = counterSlice.actions

const store = configureStore({
  reducer: counterSlice.reducer
})

// You can still subscribe to the store
store.subscribe(() => console.log(store.getState()))

// Action objects are still passed to 'dispatch', but they are created for us 
store.dispatch(incremented())
// {value: 1}
store.dispatch(incremented())
// {value: 2}
store.dispatch(decremented())
// {value: 1}

The Redux Toolkit allows us to write shorter and easier to read logic, while still following the same Redux behavior and data flow.

—END—

资源下载此资源为免费资源立即下载
Telegram:@John_Software

Disclaimer: This article is published by a third party and represents the views of the author only and has nothing to do with this website. This site does not make any guarantee or commitment to the authenticity, completeness and timeliness of this article and all or part of its content, please readers for reference only, and please verify the relevant content. The publication or republication of articles by this website for the purpose of conveying more information does not mean that it endorses its views or confirms its description, nor does it mean that this website is responsible for its authenticity.

Ictcoder Free source code Redux – A predictable state container for JavaScript applications https://ictcoder.com/kyym/redux-a-predictable-state-container-for-javascript-applications.html

Share free open-source source code

Q&A
  • 1, automatic: after taking the photo, click the (download) link to download; 2. Manual: After taking the photo, contact the seller to issue it or contact the official to find the developer to ship.
View details
  • 1, the default transaction cycle of the source code: manual delivery of goods for 1-3 days, and the user payment amount will enter the platform guarantee until the completion of the transaction or 3-7 days can be issued, in case of disputes indefinitely extend the collection amount until the dispute is resolved or refunded!
View details
  • 1. Heptalon will permanently archive the process of trading between the two parties and the snapshots of the traded goods to ensure that the transaction is true, effective and safe! 2, Seven PAWS can not guarantee such as "permanent package update", "permanent technical support" and other similar transactions after the merchant commitment, please identify the buyer; 3, in the source code at the same time there is a website demonstration and picture demonstration, and the site is inconsistent with the diagram, the default according to the diagram as the dispute evaluation basis (except for special statements or agreement); 4, in the absence of "no legitimate basis for refund", the commodity written "once sold, no support for refund" and other similar statements, shall be deemed invalid; 5, before the shooting, the transaction content agreed by the two parties on QQ can also be the basis for dispute judgment (agreement and description of the conflict, the agreement shall prevail); 6, because the chat record can be used as the basis for dispute judgment, so when the two sides contact, only communicate with the other party on the QQ and mobile phone number left on the systemhere, in case the other party does not recognize self-commitment. 7, although the probability of disputes is very small, but be sure to retain such important information as chat records, mobile phone messages, etc., in case of disputes, it is convenient for seven PAWS to intervene in rapid processing.
View details
  • 1. As a third-party intermediary platform, Qichou protects the security of the transaction and the rights and interests of both buyers and sellers according to the transaction contract (commodity description, content agreed before the transaction); 2, non-platform online trading projects, any consequences have nothing to do with mutual site; No matter the seller for any reason to require offline transactions, please contact the management report.
View details

Related Article

make a comment
No comments available at the moment
Official customer service team

To solve your worries - 24 hours online professional service