This is missing in the onSubmit event handler with reduction form 6

I am trying to use componentenet details to call an action in the submit event handler with a short form of 6.1.1, but in the event handler function I get "this" is undefined. that's what I'm doing:

class ForgetPasswordForm extends Component {
  xubmit (values) {
    console.log(this);
  }

  render() {
    const { handleSubmit } = this.props;
    return (
      <form onSubmit={ handleSubmit(this.xubmit) }>
      ...
    );
  };
}

I also tried () => handleSubmit(this.xubmit.bind(this))and this.xubmit.bind(this), as mentioned in React: this is null in the event handler , but none of them worked.

More on my setup:

  • template: create-react-app v.0.5
  • answer: v.15.3.2
  • redux: v.3.6
+4
source share
4 answers

handleSubmit.bind(this.xubmit)thus inside handleSubmit, thispoints to this.xubmit.

, .

. JavaScript

+1

handleClick, , , handleClick (fn) { fn() }, fn. . - , :

onSubmit={this.props.handleSubmit.bind(this.props.context, this.xubmit.bind(this))}

ForgetPasswordForm handleSubmit , this.xubmit this, undefined.

+1

, .

class ForgetPasswordForm extends Component {
 xubmit = (values) => {
  console.log(this);
 }

}

,

<form onSubmit={handleSubmit((values) => this.xubmit(values)) }>
+1
source

you must use class properties and arrow function together

class properties are part of stage-2

class ForgetPasswordForm extends Component {
  xubmit = (values) => {
    console.log(this);
  }

  render() {
    const { handleSubmit } = this.props;
    return <form onSubmit={ handleSubmit(this.xubmit) }>;
  };
}

Function with arrow thisfor function

0
source

Source: https://habr.com/ru/post/1660145/


All Articles