Sean's Blog

An image showing avatar

Hi, I'm Sean

這裡記錄我學習網站開發的筆記
歡迎交流 (ゝ∀・)b

LinkedInGitHub

React Redux with Class-based Components

本文介紹 React Redux 於 Class-based Components 的使用。

The Connect Function

這個 connect() 是一個 HOC,會接收一個元件。

它的寫法可以解讀為 connect() 會回傳一個 Function,接著把 Counter 元件作為參數傳進去。

1export default connect()(Counter);

除了接收元件,connect() 本身也會接受兩個 Function 作為參數:

  • 第一個參數是將 Redux State map to Props,做的事情其實就跟 useSelector 一樣
  • 第二個參數則類似 useDispatch,作用是將 dispatch 函式儲存為 Props
1import { Component } from 'react';
2import { connect } from 'react-redux';
3
4class Counter extends Component {
5  incrementHandler = () => {
6    this.props.increment();
7  };
8
9  decrementHandler = () => {
10    this.props.decrement();
11  };
12
13  render() {
14    return (
15      <main>
16        <div>{this.props.counter}</div>
17        <div>
18          <button onClick={this.incrementHandler.bind(this)}>Increment</button>
19          <button onClick={this.decrementHandler.bind(this)}>Decrement</button>
20        </div>
21      </main>
22    );
23  }
24}
25
26const mapStateToProps = (state) => {
27  return {
28    counter: state.counter,
29  };
30};
31
32const mapDispatchToProps = (dispatch) => {
33  return {
34    increment: () => dispatch({ type: 'INCREMENT' }),
35    decrement: () => dispatch({ type: 'DECREMENT' }),
36  };
37};
38
39export default connect(mapStateToProps, mapDispatchToProps)(Counter);

References