【问题标题】:How can i use destructuring assignment into map function?我如何在地图函数中使用解构赋值?
【发布时间】:2019-07-20 12:44:14
【问题描述】:
constructor(props){
    super(props)
    let Path = window.location.href.split('/')
    let name = Path[Path.length-1]
    name = name.replace(/%20/g, ' ')
    const auxKeys = Object.keys(this.props.test.aux) 
    let aux = {}

    auxKeys.map((value, key) => this.props.test.aux[value].name === name ?  
        aux = {
            val0: value,
            const {val1} = this.props.test.aux[value], //i need to do this, but doesn't work
            val2: this.props.test.aux[value].val2, //when i do this, i pass the reference of props, and when i change the state, i change the props... but if user cancel this operation, the props was changed yet
            val3: this.props.test.aux[value].val3,
            val4: this.props.test.aux[value].val4,
            val5: this.props.test.aux[value].val5
        }:
        null  
    )

    const {val0, val1, val2, val3, val4, val5} = aux 

    this.state = {
        aux: {
            val0,
            val1,
            val2,
            val3,
            val4,
            val5,

        }
    }
} 

handleChange = field => event => {
const aux = {
   ...this.state.aux,
   [field]: event.target.value
}
this.setState({aux})  //when i do this, i don't want to change the props, i want just change this.state.aux.'field'
}

我想使用解构赋值映射函数...我怎样才能正确地完成这项工作?我需要复制道具并且不要参考...我需要更改状态,而不是道具

【问题讨论】:

  • const {val1} = this.props.test.aux[value], 这不是扩展运算符,更像是对象解构。
  • 你为什么在这里使用map?你对结果数组什么都不做。为什么要在三元表达式中分配给aux
  • 对不起,我没有得到你想要的。这种无效的语法根本不清楚。输入 (this.props.test.aux) 是什么,预期输出是什么?解构、传播和map方法有什么关系?
  • @Bergi 我知道你是对的:扩展语法不是运算符,但在我的母语中,MDN 被称为spread operatorEl operador de propagación spread operator permite que una expresión sea expandida en situaciones donde se esperan múltiples argumentos (llamadas a funciones) o múltiples elementos (arrays literales)。 也许相同的翻译适用于其他语言,这会产生混淆。

标签: javascript reactjs


【解决方案1】:

你可以试试下一个:

  auxKeys.map((value, key) => this.props.test.aux[value].name === name ?  
        aux = {val0: value, ...this.props.test.aux[value]}:
        null

【讨论】:

  • 我需要复制 this.props.test.aux[value].'some',因为我会把这个值放在 state={} 中,当我改变状态时,我不会'不想改变道具......我改变了问,看那个plz
  • 如果你不想使用引用,你可以通过 Object.assign , const newAux = Object.assign({}, this.props.test.aux) 制作新的道具对象
  • 它也不起作用:/ .. 我只需要一个副本,比如const {val1} = this.props.test.aux[value]
  • 我这样做:valx: [...this.props.test.aux[value].valx]。 tnkz 为您提供帮助@MaksymKoldun
猜你喜欢
  • 2013-04-04
  • 1970-01-01
  • 1970-01-01
  • 2019-10-23
  • 2017-07-12
  • 1970-01-01
  • 2017-06-17
  • 1970-01-01
相关资源
最近更新 更多