React class 实例道具阻止使用 PureComponent

React class instance prop prevents from using PureComponent

我的 React 组件有一个道具,它是一个 class 实例,基于来自 redux 存储的数据。

这样做的原因是使用 class 及其所有自定义方法(超过 50 个)来处理这些数据要方便得多。

我不能使用 PureComponent,因为 React 总是认为这个 prop 已经改变。问题是我的大部分 React 组件都连接到这个 prop...

我知道像 reselect 这样的解决方案,但这意味着有太多(与我的 class 一样多的自定义方法)select 或仅用于操作此数据。

你有什么建议?

我的 redux select 看起来像这样:

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
}

在我的 React 组件中:

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

您尝试过使用 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 正确,那么这应该生成一个新的 WeatherStation 实例 只有当 基础数据时,即。从 getStationData 返回的内容已更改。 (而不是每次 状态中的任何东西 发生变化时都生成一个新实例。)