Detailed explanation of the use of Redux + React Redux + Redux thunk in the actual project development of React

Posted by mamuni on Tue, 25 Jan 2022 14:59:43 +0100

React is our view framework, but it is difficult to manage the data state that needs to be shared during large-scale project development. Components with obvious parent-child relationship are also more convenient to transfer values, but it is very troublesome for unrelated components to transfer values. At this time, we need to use our state management library redux, This article will explain the combined application of Redux + react Redux + Redux thunk in the actual react project development, which is also the most commonly used combination in our enterprise project development, so that you can quickly apply it!

1, Introduction to Redux

Redux is the most commonly used state management library in conjunction with React project development. As we all know, in the development of our React project, the common data state of components (such as user information, etc.) may be used by multiple components. If the relationship between components is clear (such as parent-child relationship), it is convenient to transmit, but if the relationship is not clear or there is no relationship, it will be very troublesome at this time, However, with the help of our Redux, we can store these states in the Redux store. Which component needs to be retrieved from the store, and which component wants to change the store, we can retrieve the corresponding action. The action will trigger the reducer to change the store, so that the store of each component will change.

2, Redux installation

npm i redux react-redux redux-thunk

Here we install three libraries at a time:

redux: the core library, which completes store data state management, reducer (trigger will return a new store to replace the old store) management, and action (we can't trigger the reducer directly, we need to call action to trigger the reducer) management.

React Redux: it is used to simplify the process of using Redux in react. Among them, the Provider provides the global store state and connect connector. If the store state is required, it is used to connect.

redux thunk: enables the action of redux to write asynchronous methods. Asynchronous methods cannot be written in the action itself. You can only use redux thunk.

3, Create corresponding files (store, reducer, action, action type)

Create the corresponding directories and files in the project src directory

store/index.js: create a store and pass in the reducer as the first parameter, and the application middleware Redux thunk as the second parameter. The specific code is as follows

import { createStore, applyMiddleware } from "redux";
import reducer from "./reducer";
import thunk from "redux-thunk";

const store = createStore(reducer, applyMiddleware(thunk));

export default store;

store/reducer.js: a count reducer is created. Each time an action is triggered, the value passed will be used as the second parameter. The first parameter is the old state. After the reducer is executed, the new state will replace the old state. Among them, we also introduce the combinerreducers of reducux, which is used to merge multiple reducers and finally return an integrated reducer

import { combineReducers } from "redux";
import { COUNT_ADD, COUNT_REDUCE } from "./action-type";

const initCount = {
  count: 0,
};

function count(state = initCount, action) {
  switch (action.type) {
    case COUNT_ADD:
      return state.count + 1;
    case COUNT_REDUCE:
      return state.count - 1;
    default:
      return state;
  }
}

export default combineReducers({
  count,
});

store/action.js: every time we want to change the store, we need to trigger the action first. In addition, we use Redux thunk. You can execute asynchronous methods (such as ajax data request) in action to trigger the store change of reducer. In this example, my action is relatively simple. In practice, everyone's may be more complex, but the principle is the same. An action method executes the corresponding logic (such as Ajax request or logic judgment), and finally returns an action object. The reducer will perform the corresponding store change according to the type and data of the action object

import { COUNT_ADD, COUNT_REDUCE } from "./action-type";

export const receiveCountAdd = () => ({ type: COUNT_ADD });

export const receiveCountReduce = () => ({ type: COUNT_REDUCE });

store/action-type.js: here is the type of our corresponding action object. Why should I do such a step, because we need to set the action When JS passes the action object, it should also be added in reducer JS judges the corresponding type to avoid that because the type is long and complex, the two sides are inconsistent, and the program will not report an error (because the reducer judges that if there is no corresponding type, it will go to default), so we set a constant as the type

// Self increment of count
export const COUNT_ADD = 'COUNT_ADD'

// count self subtraction
export const COUNT_REDUCE = 'COUNT_REDUCE'

At this point, the corresponding store will be created as a whole. Next, we will use it in the corresponding components.

4, Receive store and trigger action to change store in component

Before that, we need to use react Redux's Provider to provide the store status globally. Here, we directly in index JS and pass the store to its attribute store

import React from "react";
import ReactDOM from "react-dom";
import App from "./views/App";
import { Provider } from "react-redux";
import store from './store'

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

Next, we can use the connect connector in the component to obtain the store and corresponding action we need. First, we introduce connect and the corresponding action we create: receiveCountAdd. When exposing the component, use connect, which is a high-order function (the execution function returns a function), When executing the first function, there are two parameters (the first is the state to be received, here we are count, and the second is action, which is written in es6). The second function passes in our component name. After this step, the store and action we need will be attached to our props, and then we can obtain or execute it very simply (see useEffect)

import React, { useEffect } from "react";
import { connect } from "react-redux";
import { receiveCountAdd } from "../../store/action";

function Article(props) {
  useEffect(() => {
    props.receiveCountAdd();
    console.log(props.count);
  }, []);
  return <div>Article information</div>;
}

export default connect(
  (state) => ({ count: state.count }),
  { receiveCountAdd },
)(Article);

So far, the detailed explanation of the use of Redux + React Redux + Redux thunk in the actual project development of React has been completed. If you have a little partner who doesn't understand, you can leave a message!

Topics: Javascript Front-end React