Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
563 views
in Technique[技术] by (71.8m points)

reactjs - React this.state is undefined?

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.state.users but I get error

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

Component

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...