2017-07-07 20 views
0

我很苦惱這個bug。這裏是我的代碼:event.target [matches]錯誤表單在Meteor React項目中提交

這很長,所以這裏是一個簡短的版本:我有一個表單來創建一個事件,我想handleSubmit()來處理錯誤消息,如果沒有,向db添加事件。我確實導入了{Events},事實上這個表單在我做了一些修改之前就已經工作了。當我運行它時,我收到一條錯誤消息:Uncaught TypeError:event.target [matches]不是函數。感謝任何人看着這個。

export default class Create extends React.Component { 
constructor(props) { 
    super(props); 
    this.state = { 
     error: {} 
    } 

    this.handleSubmit = this.handleSubmit.bind(this); 
} 
handleSubmit(evt) { 
    evt.preventDefault(); 

    this.setState({error: {}}); 
    let title = this.refs.title.value; 
    if (!title) { 
    this.setState((prevState) => { 
     let newState = prevState; 
     newState.error.title = 'Title has to be filled up.'; 
     return newState; 
    }) 
    } 
    let description = this.refs.description.value; 
    if (!description) { 
    this.setState((prevState) => { 
     let newState = prevState; 
     newState.error.description = 'Description has to be filled up.'; 
     return newState; 
    }) 
    } 


    if (!this.state.error) { 
     Events.insert({title: title, description: description}); 
     this.props.history.push('/home'); 
    } 

和:

 <form onSubmit={this.handleSubmit} noValidate> 

     <input ref="title" type="text" name="title" placeholder="Title" 
     style={this.state.error.title ? {borderBottomColor: 'red'} : undefined}/> 
     <div className="errorText">{this.state.error.title}</div> 

     <input ref="description" type="text" name="description" placeholder="Description" 
     style={this.state.error.description ? {borderBottomColor: 'red'} : undefined}/> 
     <div className="errorText">{this.state.error.description}</div> 

     <button type="submit" className="btn btn-success">Create new event</button> 
    </form> 
+0

我前一段時間發佈了一個答案。這是一場虛驚,我仍然被這個......所迷惑......任何人? –

+0

您是否嘗試從構造函數中移除'this.handleSubmit = ...'行,爲了能夠調用this.handleSubmit,沒有必要這麼做。 – tomr

+0

我不認爲這是問題所在。儘管如此,我認爲我正在接近。它是setState是異步的,空的對象是truthy的組合。錯誤消息來自Chrome擴展。 :( –

回答

0

因此,有兩個問題代碼:

  1. 的setState是異步。它在函數執行後解析。解決方法:在開始時輸入let error = false,然後設置error = true以及setState調用。

  2. 空的物體是真的。感謝error變量,我們可以將條件更改爲if(!error)。或者if(error) {return} - 這也適用。

哦,並且錯誤信息來自chrome擴展。吮吸鉻不告訴你一個錯誤消息來自一個擴展 - 至少我不認爲它確實。

最好,