2017-10-20 92 views
2

我作出反應的應用程序需要跟蹤與動態密鑰的配置對象,所以我把它傳遞給這樣的組件:作爲道具傳遞對象會干擾componentWillReceiveProps嗎?

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

雖然這工作,當我在組件的componentWillReceiveProps(nextProps)我不能辨別配置更改,因爲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庫作爲狀態對象。