未定义是不是在构造函数()方法的对象
问题描述:
下面是我的代码未定义是不是在构造函数()方法的对象
class ApplyForm extends Component {
constructor(props) {
super(props);
this.getType = this.getType.bind(this);
this.state = {
accessToken: '',
accountsComapny: '',
type: this.getType(),
};
}
async componentDidMount() {
await this.getToken();
const token = 'Token ' + this.state.accessToken;
this.loadAccountsComapnyData(token);
}
getType() {
if (this.state.accountsComapny) { // Error Line
AccountsList = t.enums(this.state.accountsComapny.accounts);
}
return t.struct({
amount: t.Number,
Purpose: LoanPurpose,
Time: t.Number,
Frequency: Frequency,
FirstPayment: t.Date,
SelectAccount: AccountsList
});
}
render() {
return (
<Container theme={theme} style={styles.bg} >
<Content >
<View style={styles.TransactionFormcontainer}>
<Form
ref="form"
type={this.state.type}
options={options}
/>
<Button
rounded primary block
onPress={this.createNewLoan.bind(this)}
style={styles.submitBtn} textStyle={{ fontSize: 17 }}
>
Apply
</Button>
</View>
</Content>
</Image>
</Container>
);
}
}
我使用的getType()方法生成的选择框(SelectAccount场)动态选项。
但是,当我在构造函数方法中调用getType()时,会抛出错误。
未定义不是(评估 'this.state.accountsComapny')
答
您使用getType()
创建this.state
对象,并在getType()
你wan't访问它的目的。它不会工作,this.state
尚未创建。
if (this.state.accountsComapny) { // Error Line
AccountsList = t.enums(this.state.accountsComapny.accounts);
}
上述条件时你的构造假的,我看不到你使用getType()
方法的任何其他地方。你确定你需要这个条件吗?
答
制式最初硬编码的,你想要什么都像
this.state = {
accessToken: <your value>,
accountsCompany: <your value>,
type: t.struct({
amount: t.Number,
Purpose: LoanPurpose,
Time: t.Number,
Frequency: Frequency,
FirstPayment: t.Date,
SelectAccount: AccountsList
});
}
和功能componentWillUpdate更新类型() 作为
componentWillUpdate() {
type = this.getType();
}
希望这个作品。
想法是在您确定this.state.accountsCompany确实有值时调用this.getType()