【问题标题】:React add unmounted component to the arrayReact 将未安装的组件添加到数组
【发布时间】:2018-11-28 20:32:46
【问题描述】:

我正在尝试创建多个组件以供将来渲染,将 tham 添加到数组中,如下所示:

widgets.push(<TextWidget fieldData={fieldData} correctionFactor={correctionFactor} />);

但在我的组件中我得到了

TypeError:无法设置未定义的属性“FieldData”

class TextWidget extends Component {
    FieldData = null;
    CorrectionFactor = null;

    state = {
        FieldData: null, 
        CorrectionFactor: null
    }

    constructor(props) {
        this.FieldData = props.fieldData;
        this.CorrectionFactor = props.correctionFactor || 1;        
    }

    componentDidMount() {
        this.state.FieldData = this.FieldData;
        this.state.CorrectionFactor = this.CorrectionFactor;
    }
....

如果我在构造函数中像 this.state.FieldData = props.FieldData; 那样做某事,那么 react 会抱怨无法设置未安装组件的状态。

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    我认为您忘记在构造函数中调用 super() 作为第一行

    super(props);
    

    根据React docs

    您应该在任何其他语句之前调用 super(props)。否则,this.props 将在构造函数中未定义,这可能会导致错误。

    【讨论】:

      【解决方案2】:

      你犯了两个错误。

      • 首先:你应该在操作props之前调用super(props),然后使用this.props.FieldData,在定义状态时你甚至可以在constructor()中这样做,比如:

        constructor(props) {
            super(props);
            this.state = {
                FieldData: this.props.FieldData,
                CorrectionFactor: this.props.CorrectionFactor || 1
            };
        }
        
      • 第二:你不应该像以前那样设置状态:

        this.state.FieldData = this.FieldData;
        

      您应该使用this.setState()(阅读the docs),如下所示:

      this.setState({
         FieldData: this.props.FieldData,
         CorrectionFactor: this.props.CorrectionFactor
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-12-30
        • 2018-01-29
        • 2021-08-07
        • 1970-01-01
        • 1970-01-01
        • 2020-10-17
        • 1970-01-01
        相关资源
        最近更新 更多