React- Cannot read property 'setState' of undefined

前端 未结 3 1020
野的像风
野的像风 2021-02-14 08:11

for some reason, I\'m getting the error \" React- Cannot read property \'setState\' of undefined\". So this.state is never getting updated with the values that the user inputs.

相关标签:
3条回答
  • 2021-02-14 08:58

    In these event handlers, e.target is the <input> which triggered the event.

    onChangeName(e) {
        //this.state.name = e.target.name
        this.setState({ name: e.target.name});
    }
    
    onChangePassword(e) {
        //this.state.password = e.target.name
        this.setState({ password: e.target.password });
    }
    

    You get an input's value by using its value property:

    onChangeName(e) {
        this.setState({name: e.target.value});
    }
    
    onChangePassword(e) {
        this.setState({password: e.target.value});
    }
    

    You also need to ensure this is bound properly, as per the commented-out code in your constructor.


    If you give your inputs suitable name props, you replace these with a single onChange handler:

    constructor(props) {
      super(props)
      // ...
      this.onChange = this.onChange.bind(this)
    }
    
    onChange(e) {
      this.setState([e.target.name]: e.target.value})
    }
    
    render() {
      // ...
      <input type="text" name="name" value={this.state.name} onChange={this.onChange}/>
      <input type="password" name="password" value={this.state.password} onChange={this.onChange}/>
      // ...
    }
    
    0 讨论(0)
  • 2021-02-14 09:08

    edit

    If you're going to follow the pattern of binding in the constructor, make sure you use a correct constructor invocation:

    constructor (props) {
        super(props)
    

    Notice props inside the constructor.

    original answer

    Since it appears you're using ES6 component definitions, you should bind to this within the rendered component:

    <input type="text" value={this.state.name} onChange={this.onChangeName.bind(this)} />
    

    You don't need to define this stuff in the constructor:

     //this doesn't work
     //this.onChangeName = this.onChangeName.bind(this);
     //this.onChangePassword = this.onChangePassword.bind(this);
    

    It also appears that maybe you've left out some code in your example, so I'm not sure if you were trying to get rid of the unnecessary parts for the sake of example or what, but make sure your component is properly structured.

    0 讨论(0)
  • 2021-02-14 09:11

    If you use an arrow function then you won't need to bind.

    onNameChange = (e)=> {
    this.setState({name:e.target.value});
    }
    
    onPasswordChange = (e) => {
    this.setState({password:e.target.value});
    }
    
    0 讨论(0)
提交回复
热议问题