2017-09-01 121 views
7

我下面從Pluralsight初學者教程,對錶單提交的值傳遞給addUser組件的方法,我需要推動用戶名this.state.users但我得到錯誤React this.state is undefined?

App.jsx:14 Uncaught TypeError: Cannot read property 'users' of undefined 

組件

import React from 'react' 
import User from 'user' 
import Form from 'form' 

class Component extends React.Component { 
    constructor() { 
     super() 
     this.state = { 
      users: null 
     } 
    } 
    // This is triggered on form submit in different component 
    addUser(userName) { 
     console.log(userName) // correctly gives String 
     console.log(this.state) // this is undefined 
     console.log(this.state.users) // this is the error 
     // and so this code doesn't work 
     /*this.setState({ 
      users: this.state.users.concat(userName) 
     })*/ 
    } 
    render() { 
     return (
      <div> 
      <Form addUser={this.addUser}/> 
      </div> 
      ) 
    } 
} 

export default Component 
+0

'ADDUSER =(用戶名)=> {' – Andrew

+0

@Andrew爲什麼你需要以這種方式來寫? –

+0

對於此函數中的上下文自動綁定,但在這裏看起來不正確。 – Andrew

回答

19

當你叫{this.addUser},它被調用,這裏this是你的類(組件)的一個實例,因此,因爲addUser方法不會在你的類存在沒有給出錯誤你scope, 但當您使用addUser方法時,您正在使用this來更新state存在於 類(組件)的範圍內,但目前您在addUser方法的範圍內,所以它給出了一個錯誤,因爲在addUser範圍內您什麼也沒有樣的狀態,用戶等 因此,要解決這個問題,你需要綁定this當你調用addUser method.So你的方法總是知道的this實例。

因此,在你的代碼最終改變將是這樣的: -

<Form addUser={this.addUser.bind(this)}/> 

OR


您可以在構造結合 this,因爲它是當你應該intialize的事情,因爲構造方法的地方在組件呈現給 DOM時首先被調用。

所以,你可以做這樣: -

constructor(props) { 
    super(props); 
    this.state = { 
     users: null 
    } 
    this.addUser=this.addUser.bind(this); 
} 

現在爲你做之前,你可以把它叫做正常方式: -

<Form addUser={this.addUser}/> 

我希望這會工作,我向你明確了。