为什么`mapStateToProps`总是一个匿名函数?

时间:2016-08-31 16:40:50

标签: reactjs redux react-redux

在使用React with Redux的official documentation中,文档似乎始终将mapStateToProps定义为分配给变量的匿名箭头函数:

const mapStateToProps = (state, ownProps) => {
  return {
    active: ownProps.filter === state.visibilityFilter
  }
}

这似乎也是mapDispatchToProps的使用模式以及在文档和社区中传递给connect的其他函数。

似乎会更加简单,并按照传统用法来定义它:

function mapStateToProps(state, ownProps) {
  return {
    active: ownProps.filter === state.visibilityFilter
  }
}

为什么这样做?这是否有实际原因,还是仅仅是偏好?是否不赞成使用标准函数定义?

2 个答案:

答案 0 :(得分:2)

No particular reason, it's just the style that was used in writing the docs. Feel free to write your mapState function as either arrows or standard function declarations, declared standalone or declared inline. No difference either way.

答案 1 :(得分:1)

Is it really anonymous though?

const mapStateToProps = (state, ownProps) => {
  return {
    active: ownProps.filter === state.visibilityFilter
  }
}
console.log(mapStateToProps.name)

More info:

How do I write a named arrow function in ES2015?

For all intends and purpose, that mapStateToProps is going to show the right name in stack traces, as opposed to <anonymous function>.

相关问题