【问题标题】:Destruct object properties in array.map() and keep object as parameter销毁array.map() 中的对象属性并将对象保留为参数
【发布时间】:2019-06-02 18:20:47
【问题描述】:

是否可以在将对象作为参数保留在array.map() 函数中的同时破坏对象的属性?

基于this question我尝试了以下但失败(解析错误)

  this.state.files.map(((file, {param1, param2} = file), i) => (
    <div key={i}>
      <p>{param1}</p>
      <button onClick={this.editFile(file)} />
    </div>
  )

【问题讨论】:

    标签: reactjs object ecmascript-6 destructuring


    【解决方案1】:

    实现此目的的一种方法是使用default parameters syntax,如下所示:

    const test = (input, { a, b } = input) => [ a, b ]
    console.log(test({ a: 1, b: 2 })) // [ 1, 2 ]
    

    上面的函数没有传递第二个参数,所以第二个参数默认为第一个参数,然后就被销毁了。

    参数只有在声明后才能使用,所以这行不通:

    const test = ({ a, b } = input, input) => [ a, b ]
    console.log(test(undefined, { a: 1, b: 2 }))
    // Uncaught ReferenceError: input is not defined at test
    

    这也只能在不传递参数的情况下起作用,因此在将回调传递给Array#map的情况下,您必须声明所有传递的参数,以便您可以声明默认参数。

    在你的例子中,它看起来像这样:

    this.state.files.map((file, i, files, { param1, param2 } = file) => (
      <div key={i}>
        <p>{param1}</p>
        <button onClick={this.editFile(file)} />
      </div>
    ))
    

    【讨论】:

      【解决方案2】:

      不要使用 lambda 组件,而是将其变成一个这样的功能块

        this.state.files.map(((file, i) => {
          const {param1, param2} = file;
          return (
            <div key={i}>
              <p>{param1}</p>
              <button onClick={() => this.editFile(file)} />
            </div>
          )}
        )
      

      【讨论】:

        猜你喜欢
        • 2014-08-27
        • 1970-01-01
        • 1970-01-01
        • 2014-04-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-11
        相关资源
        最近更新 更多