【问题标题】:Why does Map have a return statement in this example? [duplicate]为什么 Map 在这个例子中有一个 return 语句? [复制]
【发布时间】:2019-01-31 20:12:57
【问题描述】:

学习 React 并试图欺骗这个 codepen。关于 FormCard 中的地图功能,我不明白 2 件事。

  1. 为什么这个 .map 函数有return 语句,我没有看到其他示例的返回

  2. 为什么箭头函数像之前的箭头函数那样使用花括号而不是括号

const FormCard = (props) => (

  const FormCard = (props) => (
  <div>
    {
      DATA.map((props) => {
        return <div style={{...largebox, ...flex}} key={props.id}>
          <div style={{...Photo,backgroundImage: `url(${props.photo})`}}></div>
          <div>
            <Author author={props.author}/>
            <Something bio={props.bio}/>
            <AdBox adpic={props.adpic} />
            <IconBox />
          </div>
      </div>
      })
    }
  </div>
)

【问题讨论】:

  • 所有map 回调都有一个return 语句。那些不使用的人可能正在使用箭头函数的 impicit return
  • 提示:阅读Arrow function章节。
  • 真的没有什么好的理由。相反,您发布的代码使用了非常不一致的样式。

标签: javascript reactjs arrow-functions


【解决方案1】:

这是从箭头函数返回的两种不同方式。

隐式返回:

如果正文以表达式而不是{ 开头,则被视为要返回的值。

[0,1,2,3,4,5,6].map(v => ({value:v})); // gives an array of objects with value set to v. 
[0,1,2,3,4,5,6].map(v => v*v)// gives an array of squares of the initial array. 

显式返回:

如果主体以{ 开头,则它被视为函数的主体,并且预计会返回return 语句。

[0,1,2,3,4,5,6].map(v => { return {value:v}}); // gives an array of objects with value set to v. 
[0,1,2,3,4,5,6].map(v => { return v*v})// gives an array of squares of the initial array. 

【讨论】:

  • 这个答案对箭头函数的风格做出了相关的区分:表达式副函数。
【解决方案2】:

一般来说,

array.map((arg) => { return actionWith(arg) })
array.map((arg) => actionWith(arg))

是相等的,因此如果他们只有返回,开发人员会缩小他们的函数

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-26
    • 2015-01-08
    • 2012-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多