【问题标题】:How to use state from a component 's reducer to another component如何使用从一个组件的 reducer 到另一个组件的状态
【发布时间】:2021-07-20 13:39:29
【问题描述】:

这是我的项目结构

src
 - Module1
     -action
     -components
     -reducer
- Module2
     -action
     -components
     -reducer

是否可以在Module2的组件中使用Modules1的reducer state而不用重新编写整个流程?

【问题讨论】:

    标签: reactjs redux components state


    【解决方案1】:

    是的,你可以。如果你的 redux 配置正确,connect 函数允许你使用所有模块的状态或动作。

    const mapStateToProps = (state: any) => ({
      state1: state.module1.state1,
      state2: state.module2.state2,
    });
    const mapDispatchToProps = (dispatch) => ({
      action1: dispatch.module1.action1,
      action2: dispatch.module2.action2,
    });
    
    export default connect(mapStateToProps , mapDispatchToProps)(component);
    

    【讨论】:

    • 感谢您的回复。但是如何让另一个模块的实例与其状态连接?
    • mapStateToProps 函数会将 redux 状态(全局状态)添加到组件的 props 中。要访问状态,您可以使用上面@shen 示例中的this.props.state1this.props.state2
    猜你喜欢
    • 1970-01-01
    • 2019-12-11
    • 2020-07-01
    • 2020-03-12
    • 2018-09-28
    • 1970-01-01
    • 2021-03-01
    • 2021-06-20
    • 1970-01-01
    相关资源
    最近更新 更多