我正在尝试创建多个组件以用于将来的渲染,将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;
那样工作,那么反应是抱怨无法设置已卸载组件的状态。
答案 0 :(得分:2)
您犯了两个错误。
首先::在操作道具之前,您应该先致电super(props)
,然后再使用this.props.FieldData
,即使在{{1}中也可以这样做},在定义状态时,例如:
constructor()
第二:您不应该像以前那样设置状态:
constructor(props) {
super(props);
this.state = {
FieldData: this.props.FieldData,
CorrectionFactor: this.props.CorrectionFactor || 1
};
}
您应该使用this.state.FieldData = this.FieldData;
(读为the docs),如下所示:
this.setState()
答案 1 :(得分:1)
我认为您忘了在构造函数中作为第一行调用super()
super(props);
根据React docs:
您应该在其他任何语句之前调用super(props)。否则,this.props将在构造函数中未定义,这可能会导致错误。