Redux - how do i access the app state from sub-com

2019-08-30 18:26发布

问题:

Let's say i have the following components structure:

App -> Comp1 -> Comp2 -> Comp3 -> Comp4 -> Comp5

Where App is the parent component of Comp1 which is the parent component of Comp2 and so on.

I create the store in App and connect it to Comp1 with the "connect" function from the "react-redux" library.

Now, what do i do if i want to access the app state or dispatch an action from Comp5?

The way i'm aware of is to pass the props (state and dispatch) all the way from App too Comp5 which doesn't seem to intuitive.

What is the best practice for this?

回答1:

With Redux forgot the component hierarchy you can connect the store directly to your component comp5:

import { connect } from "react-redux";

    const mapStateToProps = (state, ownProps) => {
      return {
        ...state.getExampleReducer,
        ...ownProps
      };
    };

    const mapDispatchToProps = {
     ActionsFunctions
    };

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


标签: redux