Redux - 如何从子组件访问应用程序状态? [英] Redux - how do i access the app state from sub-components?

查看:54
本文介绍了Redux - 如何从子组件访问应用程序状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下组件结构:

Let's say i have the following components structure:

应用程序 -> Comp1 -> Comp2 -> Comp3 -> Comp4 -> Comp5

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

其中AppComp1的父组件,Comp2的父组件以此类推.

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

我在 App 中创建了 store 并使用react-redux"库中的connect"函数将其连接到 Comp1.

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

现在,如果我想访问应用程序状态或从 Comp5 发送操作,我该怎么办?

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

我所知道的方式是从 AppComp5 一直传递道具(状态和调度),这似乎并不直观.

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?

推荐答案

使用 Redux 忘记了 component 层次结构 你可以将 store 直接连接到你的组件 comp5:

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 - 如何从子组件访问应用程序状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆