In redux, state in store can be retrieved in either of the following ways:

  1. Import the store file and call it directly from the componentstore.getState()methods
  2. Introduce the connect method and usemapStateToPropsMap the state to the props of the component

Here are some examples of both approaches:

import React, { Component } from 'react'
import store from '.. /store'
import { connect } from 'react-redux'

class Test extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <p>
        <h1>{this.props.count}</h1>
        <h2>{store.getState().reducer1.count}</h2>
      </p>)}}const mapStateToProps = (state) = > ({
  count: state.reducer1.count
})

export default connect(mapStateToProps)(Test)
Copy the code

Since both methods can be used to capture states, which one is better? It doesn’t really matter from a function implementation perspective, mapStateToProps is a bit better for code engineering and reuse, for example:

If you write a component that uses store.getState() to get the username state, store is the state of the current project. If you write a component that uses store.getState() to get the username state, store is the state of the current project. If you use the mapStateToProps method to insert username into props, this component can copy its props to another project without knowing where it came from.

To sum up: mapStateToProps is recommended if you want to reuse this component in other projects. Finally, here’s a classic illustration of how state flows from the store to the props of the component: