2017-12-15 3 views
0

상태 ("car")에 여러 개의 키가있는 객체가 있는데 그 중 하나가 배열 ("features")입니다. 내가하고 싶은 일이 몇 가지 있습니다.객체 내부에 중첩 된 배열의 상태 업데이트 (ReactJS)

  1. "기능 추가"버튼을 클릭 할 때마다 "기능"배열에 다른 문자열 (다른 기능)을 추가하려고합니다.
  2. 각 입력에 입력 할 때 "features"배열의 각 문자열/기능의 상태를 업데이트 할 수 있기를 원합니다.

나는이 온라인을 상당히 연구했으며 아무 것도 발견하지 못했습니다 (어쩌면 불가능하기 때문에).

handleAddFeature =() => { 
    const car = this.state.car 
    car.features.push('Your feature') 
    this.setState({ car }) 
    } 

그냥 복사본을 생성하고 자동차의 새로운 가치에 밀어

class Car extends React.Component { 

    state = { 
    car: {make: 'Toyota', model: 'Camry', features: []}, 
    } 


    handleChange = (e, index) => { 
    const value = e.target.value 
    let features = this.state.car.features.slice() // create mutable copy of array 
    features = features[index].concat(value) 
    this.setState({...this.state.car, features: features}) 
    } 

    handleAddFeature =() => { 
    let features = this.state.car.features.slice() 
    features.push('') 
    this.setState({...this.state.car, features: features}) 
    } 

    render() { 
    return (
     { 
     this.state.car.features.map((f, index) => { return <input key={index} onChange={e => this.handleChange(e, index)}>{feature}</input> 
     } 
     <button onClick={this.handleAddFeature}>Add Feature</button> 
    ) 
    } 
} 
+0

"각 입력을 입력 할 때"features "배열의 각 문자열/기능의 상태를 업데이트 할 수 있습니까? – adrice727

답변

1

좋아요,이 기능은 @ Snkendall의 대답과 매우 유사합니다. 내 handleChange 기능은 아래와 같이 표시됩니다

handleChange = (e, index,) => { 
    let array = this.state.car.features.slice() // create mutable copy of the array 
    array[index] = e.target.value // set the value of the feature at the index in question to e.target.value 
    const newObj = { ...this.state.car, features: array } // create a new object by spreading in the this.state.car and overriding features with our new array 
    this.setState({ car: newObj }) // set this.state.car to our new object 
} 

이 솔루션 사이 Snkendall의 @ 차이점은 newObj 변수의 정의입니다. 이것은 상태 객체 내부에 중첩 된 개별 키를 업데이트하는 유일한 방법입니다.

0

Ad.1 : 어느 쪽이든, 여기 내 코드입니다.

광고. 2 예 : 예 : 특색. 그는 문자열을 수정할 수있는 자신의 주를 가질 것이고 소품을 통해 데이터를 "자동차"로 추출 할 수 있습니다.

0

구성 요소에 상태가 있으면 생성자를 사용해야하며 내부에서 'this'참조를 바인딩하여 'this'가 전역을 참조하지 못하게 할 수 있습니다. 당신은 다음과 같이 당신의 상태를 포장 :

class Car extends React.Component { 
    constructor() { 
    super() 
    this.state = { 
     car: {make: 'Toyota', model: 'Camry', features: []}, 
    } 
    this.handleChange = this.handleChange.bind(this) 
    this.handleAddFeature = this.handleAddFeature.bind(this) 
    } 

이 '이'생각에 정말 좋은 기사입니다 : http://2ality.com/2017/12/alternate-this.html

또 다른 영역 당신에게 문제가 발생할 수 있습니다 features = features[index].concat(value)입니다 ... 당신이 concatting 있기 때문에 모든 변경 (키 입력)과 함께 계속 반복되는 상태에서 현재 문자열에 입력 태그의 값. 그냥 이런 배열에 해당 인덱스의 요소의 값을 재설정 할 수

handleChange = (e, index) => { 
    const value = e.target.value 
    let features = this.state.car.features.slice() 
    features[index] = value 
    this.setState({...this.state.car, features}) 
} 

그 방법은, 각각의 키는 상기 입력에서 만든 변경된 상태에 대한 값을 리셋한다. 상태가 handleChange로 이미 업데이트되었으므로 실제로 handleAddFeature를 사용할 필요가 없습니다.

저는으로 바꾸고 있습니다. ES6 구조 조정이 재미있는 일을하기 때문에 키와 값이 같으면 한 번만 참조하면됩니다. 코드를 더 DRY 한 상태로 유지하는 것은 멋진 방법입니다.

+0

자, 여기 도와 주셔서 감사 드리며 늦어서 반갑습니다. 나는 더 많은 공간이 필요했기 때문에 아래의 답에 개략적으로 제시 한 당신의 제안과 매우 유사한 것을했다. –

관련 문제