重构componentWillReceiveProps紧密耦合到React组件状态

时间:2018-12-02 15:42:25

标签: reactjs

我正在尝试在我不拥有的旧版代码库中重构组件的componentWillReceiveProps生命周期挂钩。

伪逻辑方法是:

class LegacyComp extends React.Component {
  processStatefullDataOne(nextProps) {
    const {ref1, state: {x}, props: {y}} = this;
    return doSomethingOne(ref1, x, y, nextProps);
  }
  processStatefullDataTwo(nextProps) {
    const {ref2, state: {z}, props: {w}} = this;
    return doSomethingTwo(ref2, z, w, nextProps);
  }
  componentWillReceiveProps(nextProps) {
    const s1 = this.processStatefullDataOne(nextProps);
    this.setState(s1, () => {
      const s2 = this.processStatefullDataTwo(nextProps);
      this.setState(s2);
    });
  }
}

您是否知道如何解开这段复杂的代码? 注意方法processStatefullData-x与组件内部状态紧密耦合,因此无法将其移至静态getDerivedStateFromProps:(

0 个答案:

没有答案