2017-10-20 9 views
2

동적 키를 구성 객체를 추적 할 필요가있다, 그래서 나는이 같은 구성 요소에 전달 : 나는 구성 요소의 내가 식별 할 수 componentWillReceiveProps(nextProps) 구성 변경에 오전 때물건을 받침대로 전달하는 것이 componentWillReceiveProps를 방해합니까? 응용 프로그램 반응 내

<Component configuration={this.state.configuration}> 

이, 작동하지만 this.props은 이미 nextProps으로 업데이트 되었기 때문에

알려진 문제가 아니라면 부모의 구성 상태에 대한 업데이트를 처리하는 방법과 관련이 있습니까? 구성 상태를 업데이트하는 방법은 다음과 같습니다.

handleConfigurationChangeForKey(newOption, key) { 
    const configObject = this.state.configuration; 
    configObject[key] = newOption; 
    this.setState({configuration: configObject}); 
    } 

미리 도움을 요청하십시오.

답변

2

구성 개체를 업데이트 할 때 변경 대상이 있습니다. 동일한 개체이므로 nextProps.configurationthis.props.configuration의 차이를 알 수 없습니다.

이 문제를 해결하려면 기본적으로 원본 구성 개체를 복제하고 인 것으로 변경 한 다음 setState를 사용하여 해당 새 개체에 대한 구성 지점을 만듭니다. 더 오래된 언어를 사용

handleConfigurationChangeForKey(newOption, key) { 
    const nextConfiguration = { 
    ...this.state.configuration, 
    [key]: newOption 
    }; 
    this.setState({ configuration: nextConfiguration }); 
} 

handleConfigurationChangeForKey(newOption, key) { 
    var nextConfiguration = {}; 
    nextConfiguration[key] = newOption; 
    nextConfiguration = Object.assign(
    {}, 
    this.state.configuration, 
    nextConfiguration 
); 
    this.setState({ configuration: nextConfiguration }); 
} 
+0

멋진 대답을 특징으로하는 방법과 새로운 확산 연산자를 사용하는 나를 보여 주셔서 감사합니다. – ed94133

5

this.props가 이미 nextProps로 업데이트되었으므로 구성 변경 사항을 식별 할 수 없습니다.

이것은 사실이 아닙니다. this.props에는 현재 소품 인 nextProps이 있습니다.

상태를 설정하는 방법이 문제 일 수 있습니다. Object.create 또는 딥 복사 기능 (예 : lodash에서 제공되는 기능)을 사용하여 새 구성 개체를 만들어보십시오.

const newConfig = Object.create(oldConfig) 
# or 
const newConfig = _.cloneDeep(oldConfig) 

newConfig[key] = newValue 

이렇게하면 개체가 이전 버전을 참조하여 동일하지 않게됩니다. 복사하여 성능 문제가 발생하면 상태 개체에 대해 Immutable.js 라이브러리를 사용해보십시오.