2016-12-07 30 views
0

以下は、私がのgetType()メソッドを使用して選択ボックス(SelectAccountフィールド)での動的なオプションを生成しています私のコード未定義は

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()を呼び出すと、以下のエラーがスローされます。

未定義あなたがthis.stateオブジェクトを作成getType()を使用し、getType()にあなたがそれにアクセスするためにwan't( 'this.state.accountsComapny' を評価)オブジェクト

答えて

1

ではありません。それは動作しません、this.stateはまだ作成されていません。条件の上

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

あなたのコンストラクタでfalseで、そして私はあなたがgetType()メソッドを使用し、他の場所を見ることができません。この状態が本当に必要ですか?この作品

1

メーク型が最初にハード(あなたは、関数componentWillUpdateに

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() { 
    type = this.getType(); 
} 

として希望。

アイデアはthis.state.accountsCompanyに値があることを確信しているときにthis.getType()を呼び出すことです