How to access store in second component in react-redux

后端 未结 2 1837
慢半拍i
慢半拍i 2020-12-30 06:36

I have a single component App.js where I trying to save state using redux. In index.js where I set store for only compon

相关标签:
2条回答
  • 2020-12-30 07:18

    Provider component sets the context for all its children, providing the store in it. when you use the High Order Component(HOC) connect you can wrap any component and access the store through the provided mapStateToProps and mapStateToProps no matter how nested they are. You can also access the store using context context.store but this is not recommended. Using map functions and connect, similar to what you have with your App component, is the best approach.

    0 讨论(0)
  • 2020-12-30 07:29

    When you are using Provider any component that is children of the Provider Higher Order Component can access the store properties though the use of connect function.

    So you can add the following in any component that is a child of Provider and access the score prop

    function mapStateToProps(state) {
      return { score: state.score, status: state.status };
    }
    
    export default connect(mapStateToProps)(MyComponent)
    

    However if this other component is a direct child of App component then you can also pass the score prop as a prop to this component from App like

    <MyComponent score={this.props.score}/>
    
    0 讨论(0)
提交回复
热议问题