React this.state is undefined?

前端 未结 9 2370
孤城傲影
孤城傲影 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:26

    @Vinit Raj's approaches works perfectly - tho i prefer to use the arrow function syntax like so.

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

    Using an anonymous function like this, you don't need to bind it anywhere.

    0 讨论(0)
  • 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 (
                <div>
                <Form addUser={this.addUser}/>
                </div>
                )
        }
    }
    
    export default Component
    
    0 讨论(0)
  • 2020-12-01 12:29

    I had the same problem but my issue was trying to access this.state before the this.state = { ... } call finished. Was doing something like this this.state = { ...this.function1() } and function1 = () => { a: this.state.b }. Hope this helps someone

    0 讨论(0)
提交回复
热议问题