代码之家  ›  专栏  ›  技术社区  ›  dwjohnston

总是调用构造上更新的组件?

  •  1
  • dwjohnston  · 技术社区  · 7 年前

    我一直在写这样的代码:

    class MyComponent extends Component {
    
       constructor(props) {
           super(props); 
    
           const {foo, bar, fetchFoo, fetchBar} = props; 
    
           if (!foo) {
             fetchFoo(); 
           }
    
           if (foo && foo.someCondition) {
             fetchBar(); 
           }
       }
    
    
       componentDidUpdate(prevProps) {
          if(prevProps.foo != this.props.foo && this.pros.foo.someCondition) {
             this.props.fetchBar(); 
          }
       }
    
    }
    
    
    const mapStateToProps = (
      state,
    ) => {
      return {
        foo: state.foo, 
        bar: state.bar
      };
    };
    
    const mapDispatchToProps = dispatch => {
      return {
        fetchFoo: () => dispatch(fetchFoo()), 
        fetchBar: () => dispatch(fetchBar()), 
        },
      };
    };
    
    export default connect(mapStateToProps, mapDispatchToProps)(MyComponent); 
    

    其中我的组件有两个从redux状态绑定的项- foo bar . 但我的组件需要 我可以改到另一个地方(如果他们已经填好表格的话)。

    但我不知道这两个项目是否存在于redux状态。

    所以我测试 的存在和条件 construct componentDidUpdate . 这会产生重复的代码,并且使测试更加困难。

    是让构造函数只执行 功能?打个电话就行了 this.componentDidUpdate({}) 在构造函数中?

    或者另一种整洁的方式?

    2 回复  |  直到 7 年前
        1
  •  1
  •   Paras    7 年前

    将它提取到另一个函数中,并从两个 constructor componentDidUpdate

        2
  •  0
  •   dwjohnston    7 年前

    const MyComponent = ({foo, bar, fetchFoo, fetchBar}) => {
           if (!foo) {
             fetchFoo(); 
           }
    
           if (foo && foo.someCondition) {
             fetchBar(); 
           }
    
           return (<Fragment> {JSON.stringify(foo) + JSON.stingify(bar)}</Fragment>); 
    };
    

    现在-如果你特别需要一些状态-那么你可以使用 React Hooks 介绍一些。