0

I m actually trying to develop a simple application using stores and actions and react components using fluxible and I m facing a problem.

In fact, in my component method add(), "this" is undefined...

I dont know what is the problem...

Here's my component:

import React from 'react';

class Client extends React.Component {

    constructor (props) {
      super(props);
    }

    add(e){
      this.context.dispatch('ADD_ITEM', {name:'Marvin'});
    }

    render() {
        return (
            <div>
                <h2>Client</h2>
                <p>List of all the clients</p>
                <button onClick={this.add}>Click Me</button>
                <ul>
                </ul>
            </div>
        );
    }


}

Client.contextTypes = {
    dispatch: React.PropTypes.func.isRequired
};

export default Client;
mfrachet
  • 8,772
  • 17
  • 55
  • 110

2 Answers2

0

Try this for your button:

<button onClick={this.add.bind(this)}>Click Me</button>
sma
  • 9,449
  • 8
  • 51
  • 80
0

From the docs:

Methods follow the same semantics as regular ES6 classes, meaning that they don't automatically bind this to the instance. You'll have to explicitly use .bind(this) or arrow functions =>.

So either you bind the function (which I find tedious):

<button onClick={this.add.bind(this)}>Click Me</button>

Or you can enable and leverage Babel React ES6+ arrow functions feature:

add = (e) => {
    this.context.dispatch('ADD_ITEM', {name:'Marvin'});
}
gcedo
  • 4,811
  • 1
  • 21
  • 28
  • After doing it, I have this.context is undefined... :-/ – mfrachet Sep 03 '15 at 13:11
  • Well, that depends on something else. Maybe you are missing some function call on the class? https://github.com/yahoo/fluxible#usage – gcedo Sep 03 '15 at 13:20