iT邦幫忙

2021 iThome 鐵人賽

DAY 26
0
自我挑戰組

登堂入室!前端工程師的觀念技術 _30_ 題系列 第 26

25. Redux 的用途 & 入門實作 (上)

Redux


Redux 跟 React 並沒有關係。你可以用 React、Angular、Ember、jQuery 或甚至原生 JavaScript 來撰寫 Redux 應用程式。

Redux 最基本的用途就是 集中管理state,主要的使用方式是: 將 UI 描述成一個 state 的 function,每當 state 更新,執行對應的 action。

優點

  • 大型專案管理方便
    Redux會用一個store儲存專案中所有的state,也就是資料會被集中在同一個地方。
  • 畫面和資料分離,便於整理資料
    畫面交給React Component;資料管理交給Redux。

實作步驟


修改codepen的範例,簡單製作一個姓名清單。

  1. 創建 Reducer

    • Reducer 是一個函式。
    • 在 Redux 中用以保管 state , 並指定要執行的action

    (範例有載入NODE-UUID CDNs,順便練習key綁id。)

    // 創建資料庫
    const initialState = [
      {
        name: "Winnie",
        id: uuid.v4()
      },
      {
        name: "Mary",
        id: uuid.v4()
      },
      {
        name: "Angel",
        id: uuid.v4()
      }
    ];
    
    // reducer(初始資料狀態,要對state執行的動作){}
    const reducer = (state = initState, action) => {
        switch (action.type){
            default:
                return state 
        }
    }
    

    這裡的範例只有設定預設的情況,沒有設定其他action,先簡單理解就好。

  2. 創建 store

    • store負責整合所有的 Reducer
    import { createStore } from 'redux'
    
    // 創建 store : 整合reducer
    const store = createStore(reducer, initialState);
    
    • 每個專案都應該只能有一個 store 存在。
    • 如果有不同類型的資料,會以 Reducer 區分。最後將很多 Reducer 打包並創建成 store 。

  3. 定義要從 store 中取得的資料
    mapStateToProps()

    const mapStateToProps = state => {
        return {
          contacts: state
        };
    }
    
    
    • mapStateToProps是一個函數。
    • 會把store傳進state,並回傳名為contacts的屬性(property),對應原來的屬性。
    • 每當store變化,進行重新渲染(以 contacts 為 key 從 props 流進 component)。
  4. 連結component

    • 建立Component
    const Contacts = (props) => {
        return (
          <ul>
            {props.contacts.map((contact, id) => (
              <div key={id} className="box">
                <p>{contact.name}</p>
              </div>
            ))}
          </ul>
        );
    }
    

    幫清單寫成一個Component,然後引入App。

    import React from 'react'
    
    class App extends React.Component {
      render() {
        return (
          <section className="section">
            <h1 className="title">Contacts</h1>
            <Contacts
              contacts={this.props.contacts}
            />
          </section>
        );
      }
    }
    

    傳入Contacts的this.props.contacts 就是之後mapStateToProps裡回傳的contacts屬性。

    • 連結 component 與 mapStateToProps
    import { connect } from 'react-redux'
    
    // 
    const AppContainer = connect(mapStateToProps)(App);
    

    AppContainer接收connect處理好 mapStateToProps, App的結果。

  5. 用 Provider 將 store 的資料傳進 component

    • 設置 Provider ( 一種 react-redux 中的組件 ),它會
    import { connect, Provider } from 'react-redux'
    import ReactDOM from 'react-dom'
    
    // 根據需求單將資料流進 component
    ReactDOM.render(
      <Provider store={store}>
        <AppContainer />
      </Provider>,
      document.getElementById("root")
    );
    

    Provider 是一種 react-redux 中的組件,它會

    1. 接收上方在 Redux 中創建的 store
    2. 根據和 component 綁在一起的 mapStateToProps,從 store 取出要求的資料
    3. 透過 props 流向 component

Provider 在最外層並指定了 store 。

Provider 永遠都在最外層,也永遠都只有一個

為了保持資料來源都是從 Provider 流進內部的 component ,這也是為什麼每個專案中 store 應該都只能有一個。

最後附上 codepen完整程式碼

【如內文有誤還請不吝指教>< 並感謝閱覽至此的各位:D 】

參考資料

---正文結束---


上一篇
24. 解釋 immutable / immutability
下一篇
26. Redux 的用途 & 入門實作 (下)
系列文
登堂入室!前端工程師的觀念技術 _30_ 題31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言