2017-09-27 54 views
1

My React组件具有一个prop类,它是基于来自redux存储库的数据的类实例。React类实例prop阻止使用PureComponent

原因是使用类及其所有自定义方法(超过50个)处理此数据要方便得多。

我无法使用PureComponent,因为React始终认为此道具已更改。问题是,我的React组件大部分都连接到这个支持...

我知道解决方案像重新选择,但这意味着有太多(我的类有自定义方法多)选择器只用于操作的这些数据。

你会建议什么?

我Redux的选择看起来是这样的:

getStation(state) { 
    // some logic to fetch the right station 
    return new WeatherStation(state.services.stationList[i]) 
} 

其中气象站是:

class WeatherStation { 
    constructor (data) { 
    this.station = data 
    } 

    getId() {...} 
    // many more methods 
} 

和我的阵营Compoonent内:

class MyComponent extends React.Component { 
    ... 
    const mapStateToProps = (state, ownProps) => { 
    return { 
     station: getStation(state), 
    } 
    } 
} 
+2

你可以发布你的代码的相关部分? –

+0

你有没有试过ImmutableJS? – hawk

+0

还想看代码。特别是你创建你的类实例的地方。 – jonahe

回答

0

您是否尝试过使用reselect沿着这些线路?

import { createSelector } from 'reselect'; 

getStationData(state) { 
    // some logic to fetch the right station 

    // no new instances here, just selecting the relevant data 
    return state.services.stationList[i]; 
} 


// create "memoized" selector. 
const getEnhancedStation = createSelector(
    getStationData, 
    stationData => new WeatherStation(stationData) 
) 

如果我没有理解reselectcreateSelector正确,那么这应该产生一个新的气象站实例只有基础数据,即。从getStationData返回的东西,已经改变。 (而不是每次生成新实例任何东西在状态变化。)

+1

非常感谢@jonahe,它像一个魅力。这将帮助我从组件的shouldComponentUpdate方法中删除大量不必要的代码 –

+0

没问题:)很高兴听到它的工作! – jonahe

相关问题