React this.state is undefined?

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

    The problem is in this context, so use

    <form onSubmit={(event)=>this.addUser(event)}>
       // Inputs
    </form>
    addUser(event){
       event.preventDefault()
       // Code this.state 
    }
    
    0 讨论(0)
  • 2020-12-01 12:05

    Simpley use async in function

    addUser =async (userName) => { console.log(this.state.users) }

    this will works fine

    0 讨论(0)
  • 2020-12-01 12:07

    If you prefer using arrow function do this. The arrow function syntax as like below

    addUser = event => { 
        const { value }  = event.target;
        console.log("value", value);
    }
    

    To prevent this function being called on every render or re-render you need to

    Change

    <Form addUser={this.addUser}/>
    

    To

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

    So that addUser gets called only when event is happened/triggered

    0 讨论(0)
  • 2020-12-01 12:08

    In your case by declaring your function as a fat arrow function you add context and remove the requirement to bind to this. This works just the same as the other solutions but makes things a lot simpler to both write and read. Just change...

     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)
        })*/
    }
    

    to...

    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)
        })*/
    }
    

    And everything else can stay the same.

    0 讨论(0)
  • 2020-12-01 12:19

    When you call {this.addUser} , it gets called, here this is an instance of your class(component), and thus it gives no error to you because addUser method does exist in your class scope, but when you are under addUser method you are using this to update the state which exist in the scope of class(component), but currently you are within the scope of addUser method and so it gives you an error as under addUser Scope you got nothing like state, user etc. So to deal with this problem you need to bind this while you are calling addUser method.So that your method always knows the instance of this.

    So the final change in your code will look like this:-

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

    OR


    You can bind this in the constructor,because it is the place when you should intialize things because constructor methods are called first when the components render to the DOM.

    So you can do it in this way:-

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

    And now you can call it in normal way as you did before:-

    <Form addUser={this.addUser}/>
    

    I hope this will work,And I made it clear to You.

    0 讨论(0)
  • I don't think the other answers explain this very well. Basically the problem is that Javascript's this keyword is insane (MDN very generously says it "behaves a little differently in JavaScript compared to other languages").

    The TL;DR is that this is not necessarily the class that the method is defined in. When you use this.addUser in your <Form> element, this is actually the Form object! I'm not sure why React does this - I can't really think why anyone would want that, but it's easy to verify. Just put console.log(this) in addUser and you'll find it is an instance of Form.

    Anyway the solution is pretty simple - use an arrow function. Arrow functions make a copy of this at the point where they are defined. So if you put one in your render function, as other people have suggested:

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

    Then when render() is run, this will refer to the Component object, the arrow function will make a copy of it, and then when it is run it will use that copy. It's basically a shorthand for this code (and this is what people used to do before arrow functions):

        render() {
            const that = this; // Make a copy of this.
            return (
                <div>
                <Form addUser={function() { return that.addUser; }}/>
                </div>
                )
        }
    

    Also, as other people have mentioned, creating a new function every time you call your render function might have performance implications, so it is better to capture this once somewhere else. I think this is a better approach than what other people have suggested:

    class Component extends React.Component {
        constructor() {
            super()
            this.state = {
                users: null
            }
        }
        // This is triggered on form submit in different component
        addUser = (userName) => { 
            this.setState({
                users: this.state.users.concat(userName)
            })
        }
        render() {
            return (
                <div>
                <Form addUser={this.addUser}/>
                </div>
                )
        }
    }
    

    But this is my first day using React, and I normally try to avoid using languages as completely barking as Javascript, so take all this with a pinch of salt!

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