2016-09-07 46 views
0

我正在創建一個登錄組件,它將顯示登錄錯誤。 但我不知道如何把errors陣列從_onSubmit功能LoginForm創建一個登錄組件,它將顯示登錄錯誤

這裏我的代碼。

import React, { Component } from 'react'; 
import Split from 'grommet/components/Split'; 
import Section from 'grommet/components/Section'; 
import Sidebar from 'grommet/components/Sidebar'; 
import LoginForm from 'grommet/components/LoginForm'; 
//import Logo from './Logo'; 
import firebase from 'firebase'; 
export default class Login extends Component { 

    constructor() { 
    super(); 
    this._onSubmit = this._onSubmit.bind(this); 
    this._onResponsive = this._onResponsive.bind(this); 
    this.state = {responsive: 'multiple',errors:[]}; 
    } 

    _onSubmit(fields) { 


    firebase.auth().signInWithEmailAndPassword(fields.username, fields.password).catch(function(error) { 
     // Handle Errors here. 
     var errorCode = error.code; 
     var errorMessage = error.message; 
     var errors = []; 

     errors.push(errorCode); 
     errors.push(errorMessage); 
     console.log(errors); 


     // How to bring the errors from here to ?????? 
    }); 
    } 

    _onResponsive(responsive) { 
    this.setState({responsive: responsive}); 
    } 

    render() { 

    var image; 
    if ('multiple' === this.state.responsive) { 
     image = <Section full={true} pad="none" texture="url(img/grafitti.jpg)" />; 
    } 


    return (
     <Split flex="left" separator={true} onResponsive={this._onResponsive}> 
     {image} 
     <Sidebar justify="center" align="center" pad="medium" size="large"> 
      <LoginForm 

      title="Ferret" 
      onSubmit={this._onSubmit} 
      errors={??????} /> 
     </Sidebar> 
     </Split> 
    ); 
    } 
} 

有人可以指導嗎?謝謝!!!

+0

這是什麼編程語言? –

+0

這不是一個好的架構,請考慮使用Redux代替,從演示組件分派動作以更新存儲中的應用程序狀態,執行異步動作 – RMontes13

回答

1

這裏的問題是,當您在.catch()處理函數中引入函數時,您正在創建閉包。

您正確地結合你的this_onSubmit功能,但是從你與function() {}創建的閉包內,你的this不綁定到外部範圍。

你必須使用arrow function,不創建的選項詞彙是:

firebase 
    .auth() 
    .signInWithEmailAndPassword(fields.username, fields.password) 
    .catch((error) => { 
    ... 
    // Now works since the arrow function does not create a new lexical this 
    this.setState({}) 
    }); 

,或者你可以bind的外this(你期望有一個setState()功能之一)至內部關閉:

firebase 
    .auth() 
    .signInWithEmailAndPassword(fields.username, fields.password) 
    .catch(function(error) { 
    this.setState({}) // Is now bound to the outer this 
    }.bind(this)); 
+0

非常感謝你。 – John

+0

隨時!祝一切順利! –

0

只需將state.errors作爲道具傳遞給您的子組件即可。

<LoginForm 
     title="Ferret" 
     onSubmit={this._onSubmit} 
     errors={this.state.errors} /> 

請確保在LoginForm中傳遞的值是空數組時不顯示錯誤。

+0

當出現錯誤時,我認爲我需要在函數_onSubmit內設置setState,如: this.setState({errors:errors})。但我得到錯誤:Uncaught TypeError:無法讀取未定義的屬性'setState' – John

+0

我認爲這是因爲您在catch塊中傳遞函數(錯誤)。嘗試並使用像這樣的.catch((error)=> {code goes here和this.setState})的箭頭函數。基本上,你在這個代碼塊中執行this.setState,這不會引用類。我認爲另一種方法是做fucntion(錯誤,這),但我不知道 – Kafo