2016-12-07 65 views
0

下面是我的代碼未定義是不是在構造函數()方法的對象

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

回答

1

您使用getType()創建this.state對象,並在getType()你wan't訪問它的目的。它不會工作,this.state尚未創建。

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

上述條件時你的構造假的,我看不到你使用getType()方法的任何其他地方。你確定你需要這個條件嗎?

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

相關問題