Redux - how do i access the app state from sub-components?

依然范特西╮ 提交于 2019-12-13 03:49:48

问题


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);


来源:https://stackoverflow.com/questions/54239359/redux-how-do-i-access-the-app-state-from-sub-components

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!