如何在地图功能中使用解构分配?

时间:2019-02-26 21:41:28

标签: javascript reactjs

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'
}

我想使用分解分配内部地图功能...我该如何正确地进行这项工作?我需要复制道具而不参考...我需要更改状态,而不是道具

1 个答案:

答案 0 :(得分:0)

您可以尝试下一个:

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