[Front-end knowledge] React foundation consolidation (33) - detailed explanation of the use of Redux

React foundation consolidation (thirty-three) - detailed explanation of the use of Redux

Detailed use of Redux

  1. For React 基础巩固(三十二)the case in , we hope to extract the common code in the page (such as the code below), and use high-level components to intercept it uniformly.

    constructor() {
          
          
      super();
    
      this.state = {
          
          
        counter: store.getState().counter,
      };
    }
    componentDidMount() {
          
          
      store.subscribe(() => {
          
          
        const state = store.getState();
        this.setState({
          
          
          counter: state.counter,
        });
      });
    }
    
  2. In order to connect react and redux, install a toolreact-redux

    npm install react-redux
    
  3. Use react-redux, uniformly inject store in index.js

    import React from "react";
    import ReactDOM from "react-dom/client";
    import App from "./App";
    import {
          
           Provider } from "react-redux";
    import store from './store'
    
    const root = ReactDOM.createRoot(document.getElementById("root"));
    root.render(
      <React.StrictMode>
      <Provider store={
          
          store}>
      <App />
      </Provider>
    </React.StrictMode>
    );
    
    
  4. Create a new about.js page by react-reduxintroducing store

    import React, {
          
           PureComponent } from "react";
    import {
          
           connect } from "react-redux";
    
    export class about extends PureComponent {
          
          
      render() {
          
          
        const {
          
           counter } = this.props;
        return (
          <div>
            <div>About: {
          
          counter}</div>
          </div>
        );
      }
    }
    
    // connect()的返回值是一个高阶函数
    const mapStateToProps = (state) => ({
          
          
      counter: state.counter,
    });
    
    export default connect(mapStateToProps)(about);
    
    
  5. Introduce a new about.jsx page in App.jsx to see the running effect

    import React, {
          
           PureComponent } from "react";
    import Home from "./pages/home";
    import Profile from "./pages/profile";
    import About from "./pages/about";
    import "./style.css";
    import store from "./store";
    
    export class App extends PureComponent {
          
          
      constructor() {
          
          
        super();
    
        this.state = {
          
          
          counter: store.getState().counter,
        };
      }
      componentDidMount() {
          
          
        store.subscribe(() => {
          
          
          const state = store.getState();
          this.setState({
          
          
            counter: state.counter,
          });
        });
      }
      render() {
          
          
        const {
          
           counter } = this.state;
        return (
          <div>
            <h2>App Counter: {
          
          counter}</h2>
    
            <div className="pages">
              <Home />
              <Profile />
              <About />
            </div>
          </div>
        );
      }
    }
    
    export default App;
    
    

running result
6. Continue to optimize the code, using react-reduxthe connect in the decoupling of state and dispatch. In 基础巩固(三二)the home.jsx page in , state and dispatch are represented as follows:

import React, {
    
     PureComponent } from "react";
import store from "../store";
import {
    
     addNumberAction } from "../store/actionCreators";
export class home extends PureComponent {
    
    
  constructor() {
    
    
    super();

    this.state = {
    
    
      counter: store.getState().counter,
    };
  }
  componentDidMount() {
    
    
    store.subscribe(() => {
    
    
      const state = store.getState();
      this.setState({
    
    
        counter: state.counter,
      });
    });
  }

  addNumber(num) {
    
    
    store.dispatch(addNumberAction(num));
  }

  render() {
    
    
    const {
    
     counter } = this.state;
    return (
      <div>
        home counter:{
    
    counter}
        <div>
          <button onClick={
    
    (e) => this.addNumber(1)}>+1</button>
          <button onClick={
    
    (e) => this.addNumber(5)}>+5</button>
          <button onClick={
    
    (e) => this.addNumber(8)}>+8</button>
        </div>
      </div>
    );
  }
}

export default home;

In order to decouple the page from the store, in about.jsx, we no longer use state and dispatch in the way of home.jsx. The optimization is as follows:

import React, {
    
     PureComponent } from "react";
import {
    
     connect } from "react-redux";
import {
    
     addNumberAction, subNumberAction } from "../store/actionCreators";

export class about extends PureComponent {
    
    
  calcNumber(num, isAdd) {
    
    
    if (isAdd) {
    
    
      this.props.addNumber(num);
    } else {
    
    
      this.props.subNumber(num);
    }
  }

  render() {
    
    
    const {
    
     counter } = this.props;
    return (
      <div>
        <h2>About: {
    
    counter}</h2>
        <div>
          <button onClick={
    
    (e) => this.calcNumber(6, true)}>+6</button>
          <button onClick={
    
    (e) => this.calcNumber(6, false)}>-6</button>
          <button onClick={
    
    (e) => this.calcNumber(8, true)}>+8</button>
          <button onClick={
    
    (e) => this.calcNumber(8, false)}>-8</button>
        </div>
      </div>
    );
  }
}

// connect()的返回值是一个高阶函数
// 映射state到props
const mapStateToProps = (state) => ({
    
    
  counter: state.counter,
});

// 映射dispatch到props
const mapDispatchToProps = (dispatch) => ({
    
    
  addNumber(num) {
    
    
    dispatch(addNumberAction(num));
  },
  subNumber(num) {
    
    
    dispatch(subNumberAction(num));
  },
});

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

  1. View running results
    operation result

Guess you like

Origin blog.csdn.net/weixin_42919342/article/details/131927731