mapstatetoprops 和 mapdispatchtoprops 有什么区别 [英] What's the Difference between mapstatetoprops and mapdispatchtoprops

查看:31
本文介绍了mapstatetoprops 和 mapdispatchtoprops 有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

connect 函数的 mapStateToPropsmapDispatchToProps 参数有什么区别在反应 redux 中?谁能用例子给出合适的解释

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

推荐答案

mapStateToProps 是一个用于向组件提供存储数据的函数,而 mapDispatchToProps是您将用来向组件提供动作创建者作为道具的东西.

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.

根据文档:

如果指定了 mapStateToProps 参数,则新组件将订阅 Redux 商店更新.这意味着任何时候商店被更新,mapStateToProps 将被调用.结果mapStateToProps 必须是一个普通对象,它将被合并到组件的 props.

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.

使用 mapDispatchToProps 每个动作创建者都被包裹在一个分派中调用以便它们可以被直接调用,将​​被合并到组件的道具.

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

一个简单的例子是

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

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

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

这篇关于mapstatetoprops 和 mapdispatchtoprops 有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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