gpt4 book ai didi

reactjs - 为什么 mapStateToProps 和 mapDispatchToProps 不仅仅是 Redux 中的一个函数?

转载 作者:行者123 更新时间:2023-12-03 13:19:04 25 4
gpt4 key购买 nike

有人可以向我解释一下为什么 Redux 有两个函数 mapStateToPropsmapDispatchToProps ,这两个函数都向容器添加 props 吗?

定义:

mapStateToProps is a utility which helps your component get updated state (which is updated by some other components)

mapDispatchToProps is a utility which will help your component to fire an action event (dispatching action which may cause change of application state)

为什么 Redux 团队选择将其分成两个映射函数 - 即为什么不只使用一个函数 mapToProps(state,dispatch,props) 来完成这两个任务?

  • 这只是关注点分离/更容易理解原因吗?
  • 是否是因为 mapDispatchToProps 中重新绑定(bind)的性能问题导致每次更改都会创建新函数?为 Action 创建绑定(bind)提供单独的功能将有助于避免这项额外的工作?考虑到每次状态更改时都会调用 mapStateToProps

示例:

const increaseAction = { type: 'increase' }

class Counter extends Component {
render() {
const { value, onIncreaseClick } = this.props
return (
<div>
<span>{value}</span>
<button onClick={onIncreaseClick}>Increase</button>
</div>
)
}
}

function mapDispatchToProps(dispatch) {
return {
onIncreaseClick: () => dispatch(increaseAction)
}

}

查看此Redux example on codesandbox

最佳答案

@Andrey Prokhorov 是对的,你问的很有趣。今天早些时候,我发现自己陷入了 github issues 的深渊,并发现了这个问题 ( Add state as the third parameter to mapDispatchToProps )。虽然标题似乎没有相关性,但如果你仔细研究一下评论,gaearon(react-redux 的创建者)解释道:

Please take a look at #1. This option has been considered and rejected. Yes, it's very bad for performance to re-bind action creator on every dispatch, which is what will happen if we let people access the state in the same place they bind action creators. Technically they can still do it now with mergeProps but it's hidden well enough that people who aren't experienced with Redux don't discover it by mistake.

我还链接到了 gaearon 链接到的react-redux 的第一个问题,其中讨论了该问题(实际上是 github 上的react-redux 问题#1)。我确信他们可以将其更改为您所描述的方式,但我认为 gaearon 的评论总结了这一点:

The goal of this library is to encourage performant patterns because otherwise people will say “Redux is slow!” even if the cause is their suboptimal function binding code. We don’t want this to happen, so we’d rather make certain unperformant cases harder to implement.

关于reactjs - 为什么 mapStateToProps 和 mapDispatchToProps 不仅仅是 Redux 中的一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47500982/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com