React this.state is undefined?

前端 未结 9 2372
孤城傲影
孤城傲影 2020-12-01 11:29

I am following a beginner tutorial from Pluralsight, on form submit a value is passed to addUser component method and I need to push userName to this.stat

9条回答
  •  情深已故
    2020-12-01 12:28

    A good pattern is to bind a method to the class in the constructor function. See https://reactjs.org/docs/handling-events.html

    import React from 'react'
    import User from 'user'
    import Form from 'form'
    
    class Component extends React.Component {
        constructor() {
            super()
            this.state = {
                users: null
            }
      this.addUser = this.addUser.bind(this); 
      //bind functions which need access to "this"v in the constructor here. 
    
        }
        // 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 (
                
    ) } } export default Component

提交回复
热议问题