简体   繁体   中英

Cannot read property 'setState' of undefined, inside Object.keys, react

I'm using: method = () => { } so i don't need to bind the function

here's my class:

class Form extends Component {

  constructor(props) {
    super(props);

    this.state = {
      disabledFields: [],
    };

  }

  executeCode = ( methodCode ='', params = {} ) => {
    const result = crudCode[methodCode](params);
    if (result && result.newStates) {

      Object.keys(result.newStates).map(function(keyName, keyIndex) {
          this.setState( {  nada: 'nada' });
        });
    }
  }

I get this error:

TypeError: Cannot read property 'setState' of undefined
> 48 |         this.setState( {  nada: 'nada' });

what I'm doing wrong, I've already used this type of function and setState, but i don't know this time it does not work.

You don't use an arrow function in your map callback:

Object.keys(result.newStates).map(function(keyName, keyIndex) {
    this.setState( {  nada: 'nada' });
});

So, it is not bound to this .

This will work instead:

Object.keys(result.newStates).map((keyName, keyIndex) => {
    this.setState( {  nada: 'nada' });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM