【问题标题】:How to put constants in React components, wrapped in recompose如何将常量放入 React 组件中,包装在 recompose 中
【发布时间】:2018-08-15 18:45:13
【问题描述】:

如何编写组件特定常量 STATUS,您可以设置 this.state.status?我认为问题在于这个上下文。如果this.STATUS 被硬编码在字符串中,它可以工作。

import { compose } from 'recompose';
import React, { Component } from 'react';

class TestComponent extends Component {
    static propTypes = {};

    // can you put the STATUS constant on the component?
    static STATUS = {
        SENT: 'SENT',
        ERROR: 'ERROR',
    };

    state = { status: null };

    // functions cannot use this.STATUS
    f = () => {
        this.setState({status: this.STATUS.SENT});
        // undefined is not an object (evaluating '_this.STATUS.SENT')
    }

    render() {
        const { msg } = this.statusMessage();
        return ();
    }

}

export default compose(
  withRouter,
  connect(() => ())
)(TestComponent);

【问题讨论】:

    标签: javascript reactjs static


    【解决方案1】:

    因为STATUS是类的static property,所以你必须按如下方式访问它:

    this.constructor.STATUS.SENT
    

    如果您将其声明为实例的属性,则可以通过this.status 访问它:

    STATUS = {
      SENT: 'SENT',
      ERROR: 'ERROR',
    };
    

    或通过getter

    get STATUS() {
      return {
        SENT: 'SENT',
        ERROR: 'ERROR'
      };
    }
    

    【讨论】:

      【解决方案2】:

      为什么不直接将SENTError 设置为您的状态?

      像这样:

      this.setState({
       SEND: 'SENT'
       ERROR: 'ERROR'
       status: null
      });
      

      在你像这样直接设置你的状态之后:

      f = () => {
          const { SENT } = this.state
          this.setState({status: SENT});
      }
      

      干杯

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-12-24
        • 2019-06-01
        • 2019-01-25
        • 2020-06-23
        • 1970-01-01
        • 2019-03-31
        • 2021-08-21
        • 2019-10-18
        相关资源
        最近更新 更多