bindActionCreators, @connect in React-Redux and understanding the code

Viewed 59

I was trying to comprehend this code on github

Here they programmer have used something like this

 constructor(props) {
    super(props);
    this.actions = bindActionCreators(Actions, this.props.dispatch);
  }

Question 1: Here, this.actions = bindActionCreators(Actions, this.props.dispatch); doesn't make sense to me

Also, This isn't primary question but from where I learned React-redux, we used to connect component like this

export default connect(mapStateToProps, 
  {fetchCoin, 
    updateCrypto, 
    CurrencyRate,
    CurrencyState
  })(cryptoTicker);

In the above code Snippet the programmer have done something like this

@connect(state => {
  return {
    score: state.game.get("score"),
    result: state.game.get("result")
  };
})

Question 2: ** Which again sort of looks alien to me (like I have few months of experience using js but this is the first time I am encountering **@) So can someone please explain me what is @ in general in JS?

And lastly he have declared two functions which are being called onclick after return statement of class

 _handleNewGame = () => {
    this.actions.initGame();
  }

  /**
   * Save the current game`s state.
   */
  _handleSaveGame = () => {
    this.actions.saveGame();
  }

Now Since I am still relatively new to JS and react, I have two questions for this part

Question 3: Can we create a function inside a class after return and render? If yes then wouldn't it have been a good practise (in general) to create a function before render where all the other functions are declared?

1 Answers

For question #1 and #2, your '@connect' and 'connect(mapStateToProps, ...)(cryptoTicker)' syntax is equivalent. The @ indicates to the parser that we're using a decorator for our function, the connect(...) function, and outputs the same class, in this case Game, but with added functionality. This is called a HoC (Higher Order Components) design pattern and you can read more about it here https://medium.com/@mappmechanic/react-utility-higher-order-components-as-decorators-tc39-stage-2-9e9f3a17688a

For question #3, you are correct, it is better practice to leave the render function for the last function in the component.

Related