banner
leoking

leoking

前端开发者
tg_channel

How to use Redux in React class components and function components

Before you start, please make sure you have correctly installed Redux and its related dependencies (such as redux, react-redux, etc.), and have also created the data store, actions, and reducers. How to use store in React

1. React Class Components and Redux#

First, you need to connect the component to Redux using the connect higher-order component. The two main parameters of connect are mapStateToProps and mapDispatchToProps. mapStateToProps is used to select the state fragments you need from the Redux store and map them to the component's props. mapDispatchToProps is used to associate the created action creators with the component's props. Here is a simple example:

// First, import dependencies:
import React from 'react';
import { connect } from 'react-redux';
import { sampleActionCreator } from './actions';

// Then, the class component:

class SampleComponent extends React.Component {
  onButtonClick = () => {
    this.props.sampleActionCreator();
  };

  render() {
    const { dataFromReduxStore } = this.props;

    return (
      <div>
        <button onClick={this.onButtonClick}>Trigger Redux Action</button>
        <p>Data from Redux store: {dataFromReduxStore}</p>
      </div>
    );
  }
}

// Next, connect the component to Redux:

const mapStateToProps = (state) => ({
  dataFromReduxStore: state.sampleReducer.data,
});

const mapDispatchToProps = {
  sampleActionCreator,
};

export default connect(mapStateToProps, mapDispatchToProps)(SampleComponent);

2. React Functional Components and Redux#

In functional components, you can use the useSelector and useDispatch hooks provided by react-redux to connect to Redux.

// First, import dependencies:
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { sampleActionCreator } from './actions';

// Then, the functional component:

const SampleComponent = () => {
  const dataFromReduxStore = useSelector((state) => state.sampleReducer.data);
  const dispatch = useDispatch();

  const onButtonClick = () => {
    dispatch(sampleActionCreator());
  };

  return (
    <div>
      <button onClick={onButtonClick}>Trigger Redux Action</button>
      <p>Data from Redux store: {dataFromReduxStore}</p>
    </div>
  );
};

export default SampleComponent;

The above is the method of using Redux in React class components and functional components. The main difference between these two methods is that they use different patterns (class components use the connect higher-order component and mapStateToProps/mapDispatchToProps, while functional components use the useSelector and useDispatch hooks) to achieve state selection and action creator functionality.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.