簡體   English   中英

bindActionCreators、React-Redux 中的@connect 和理解代碼

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

我試圖在github上理解這段代碼

在這里,他們程序員使用了這樣的東西

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

問題1:這里, this.actions = bindActionCreators(Actions, this.props.dispatch); 對我來說沒有意義

此外,這不是主要問題,但從我學習 React-redux 的地方,我們曾經像這樣連接組件

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

在上面的代碼片段中程序員做了這樣的事情

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

問題 2:** 這對我來說又有點陌生(就像我有幾個月使用 js 的經驗,但這是我第一次遇到 ** @ )所以有人可以解釋一下@在 JS 中的一般含義嗎?

最后他聲明了兩個函數,它們在類的 return 語句之后被調用onclick

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

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

現在由於我對 JS 和反應還比較陌生,所以我對這部分有兩個問題

問題3:我們可以在返回和渲染后在類中創建一個函數嗎? 如果是,那么在聲明所有其他函數的地方在渲染之前創建一個函數不是一個好習慣(通常)嗎?

對於問題 #1 和 #2,您的 '@connect' 和 'connect(mapStateToProps, ...)(cryptoTicker)' 語法是等效的。 @ 向解析器表明我們正在為我們的函數、connect(...) 函數使用裝飾器,並輸出相同的類,在本例中為 Game,但具有附加功能。 這稱為 HoC(高階組件)設計模式,您可以在此處閱讀有關它的更多信息https://medium.com/@mappmechanic/react-utility-higher-order-components-as-decorators-tc39-stage-2 -9e9f3a17688a

對於問題#3,您是對的,最好將渲染函數留給組件中的最后一個函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM