What's the Difference between mapstatetoprops and mapdispatchtoprops [duplicate]

假如想象 提交于 2019-12-18 10:28:22

问题


What's the difference between mapStateToProps and mapDispatchToProps arguments to the connect function in react redux ?? Can anyone give a suitable explanation with examples


回答1:


mapStateToProps is a function that you would use to provide the store data to your component, whereas mapDispatchToProps is something that you will use to provide the action creators as props to your component.

According to the docs:

If mapStateToProps argument is specified, the new component will subscribe to Redux store updates. This means that any time the store is updated, mapStateToProps will be called. The results of mapStateToProps must be a plain object, which will be merged into the component’s props.

With mapDispatchToProps every action creator wrapped into a dispatch call so they may be invoked directly, will be merged into the component’s props.

A simple example would be

function mapStateToProps(state) {
  return { todos: state.todos }
}

function mapDispatchToProps(dispatch) {
  return { addTodo: bindActionCreators(addTodo, dispatch) }
}

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



回答2:


In a very simple term,

mapStateToProps: It connects redux state to props of react component.

mapDispatchToProps: It connects redux actions to react props.

A really light example: ( I hope, you know what I mean)

// state
const mapStateToProps = state => {
  return { lists: state.lists };
};

// props
const mapDispatchToProps = ({ lists }) => (
  <ul>
    { 
      lists.map(el => (
        <li key={ el.id }>
          { el.heading }
        </li>
      )
    }
  </ul>
);

// Now, connect state to prop
const List = connect(mapStateToProps)(mapDispatchToProps);



回答3:


In very simple terms:

mapStateToProps is called when you want to get the value of the global state from your component

function mapStateToProps(state) {
  return {
    message: state.message

  };
}

The value of the global state is only changed with the help of an action. So if you want to change the value of global state you need an action. mapDispatchToProps is used to bind action in your component.



来源:https://stackoverflow.com/questions/49994197/whats-the-difference-between-mapstatetoprops-and-mapdispatchtoprops

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