简体   繁体   English

了解 React-Redux 中的 mapStateToProps 和 mapDispatchToProps

[英]Understanding mapStateToProps & mapDispatchToProps in React-Redux

I'm trying to understand the connect() method of react-redux .我试图了解react-reduxconnect()方法。 Usually it takes two function as argument: mapStateToProps() & mapDispatchToProps() .通常它需要两个 function 作为参数: mapStateToProps() & mapDispatchToProps() I write a example for myself, here is connect() section of my User component:我为自己编写了一个示例,这是我的User组件的connect()部分:

//imports...

class User extends Component {
    /* constructor, JSX, other functions... */
}
const mapStateToProps = (state) => {
   return {
     users: state.UserReducer
   };
};

const mapDispatchToProps = (dispatch) => ({
  deleteUser: (id) => dispatch(deleteUser(id))
});

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

According to Docs I have taken the following two conclusions about mapStateToProps() & mapDispatchToProps() :根据 文档,我对mapStateToProps()mapDispatchToProps()得出以下两个结论:

  • mapStateToProps() : it makes that state available in our component. mapStateToProps() :它使 state 在我们的组件中可用。 ie it is used to pass reducer to component.即它用于将reducer传递给组件。
  • mapDispatchToProps() : it maps component relevant functions to action functions, ie with this function We can perform the action that we want in our component . mapDispatchToProps() :它将组件相关函数映射到action函数,即使用这个 function 我们可以在我们的component中执行我们想要的action

is my conclusions correct?我的结论正确吗?

React components accept data from outside via props . React 组件通过props接受来自外部的数据。 maptStateToProps and mapDispatchToProps , literally, pass the selected state properties and actions that are needed inside your component as props. maptStateToPropsmapDispatchToProps从字面上看,将组件内所需的选定 state 属性和操作作为道具传递。 The state values and actions passed to the component are available in the props of the component.传递给组件的 state 值和操作在组件的 props 中可用。 In your example, you can use this.props.users or this.props.deleteUser() .在您的示例中,您可以使用this.props.usersthis.props.deleteUser()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM