[英]Use of curly braces in signature of pure function
I'm trying to figure out how the code below works in terms of the { active, children, onClick }
. 我正在尝试根据
{ active, children, onClick }
来确定以下代码的工作方式。 What are the curly braces doing here? 花括号在这里做什么? I would have expected instead
const Link = (props) =>
, where the values are accessed in the function using props.active etc. This is what I am doing in my CommentBox example below. 我本来希望
const Link = (props) =>
,在其中使用props.active等在函数中访问值。这就是我在下面的CommentBox示例中所做的事情。
Link: 链接:
import React, { PropTypes } from 'react'
const Link = ({ active, children, onClick }) => {
if (active) {
return <span>{children}</span>
}
return (
<a href="#"
onClick={e => {
e.preventDefault()
onClick()
}}
>
{children}
</a>
)
}
FilterLink: FilterLink:
import { connect } from 'react-redux'
import { setVisibilityFilter } from '../actions'
import Link from '../components/Link'
const mapStateToProps = (state, ownProps) => {
return {
active: ownProps.filter === state.visibilityFilter
}
}
const mapDispatchToProps = (dispatch, ownProps) => {
return {
onClick: () => {
dispatch(setVisibilityFilter(ownProps.filter))
}
}
}
const FilterLink = connect(
mapStateToProps,
mapDispatchToProps
)(Link)
export default FilterLink
http://redux.js.org/docs/basics/ExampleTodoList.html http://redux.js.org/docs/basics/ExampleTodoList.html
CommentBox: 评论框:
const CommentBox = ( props ) =>
<div className="commentBox">
<h1>Comments</h1>
{ props.comments.valueSeq().map( (comment) =>
<Comment author={comment.author} key={comment.id}>
{comment.text}
</Comment>
)}
<CommentForm />
</div>
function mapStateToProps(state) {
return {comments: state.get('comments')};
}
const Link = ({ active, children, onClick }) => { ... });
What this is doing is destructuring the first argument. 这是在破坏第一个论点。 Assuming your first argument is an object with at least
active
, children
and onClick
properties, it directly maps them into variables of the same name. 假设您的第一个参数是一个至少具有
active
, children
和onClick
属性的对象,它将直接将它们映射到相同名称的变量中。
You can see it in action here . 您可以在此处查看它的运行情况。
// ES6
function foo({bar, baz}, bam){
console.log(bar, baz)
}
// ES5
"use strict";
function foo(_ref, bam) {
var bar = _ref.bar;
var baz = _ref.baz;
console.log(bar, baz, bam);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.