Undefined不是constructor()方法中的Object

时间:2016-12-07 09:23:21

标签: reactjs react-native

以下是我的代码

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()时,它会抛出错误。

  

Undefined不是Object(评估'this.state.accountsComapny')

2 个答案:

答案 0 :(得分:1)

您使用getType()创建this.state对象,而getType()则无法访问它。它不会工作,this.state尚未创建。

if (this.state.accountsComapny) {   // Error Line
    AccountsList = t.enums(this.state.accountsComapny.accounts);
}

您的构造函数中的上述条件为false,我看不到您使用getType()方法的任何其他位置。你确定你需要这个条件吗?

答案 1 :(得分:1)

使类型最初硬编码你想要的东西

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()