react整合原生redux(一)

react整合原生redux(一)

項目創建

create-react-app reduxdemo

依賴包

yarn add redux -s

思路

  1. 通過redux創建全局唯一store
  2. 通過store獲取所需數據
  3. 通過dispatch分發action對象引起store的state改變
  4. 通過store的subscribe改變視圖層

src文件目錄

|-app.js
|-store.js
|-index.js

刪減index.js

通過create-react-app創建的項目有許多無用的東西,首先將src目錄清理如上文件內容,然後將index.js精簡如下

// index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./app";

ReactDOM.render(<App />, document.getElementById("root"));

創建store

store.js是redux的核心文件,本文用於學習,不強調代碼細拆分,故reducer和store寫在一起

// store.js
import { createStore, applyMiddleware } from "redux";
import { composeWithDevTools } from "redux-devtools-extension"; //chrome redux調試工具

// state初始值
const initState = {
  list: ["a", "b"]
};

// reducer格式
const reducer = (state = initState, action) => {
  const { type, payload } = action;
  // action的type處理
  if (type === "SAVE") {
    return Object.assign({}, state, payload);
  }
  return state;
};

/**
 * 實例化store
 * 參數1: reducer
 * 參數2: 中間件
 */
export default createStore(reducer, composeWithDevTools(applyMiddleware()));

應用代碼app.js

// app.js
import React, { useState, useEffect } from "react";
import store from "./store";

export default () => {
  // 獲取store中的state,並放進hook函數,類似this.setState(store.getState())
  const [state, setState] = useState(store.getState());
  useEffect(() => {
    // store訂閱函數,當state通過store.dispatch分發action改變時此函數自動執行
    store.subscribe(() => {
      setState(store.getState()); //重新設置組件state的值,使視圖更新
    });
  }, []); // []表示只執行一次

  const { list } = state;

  const addList = () => {
    list.push(Date.now());
    store.dispatch({ type: "SAVE", payload: { list } }); //分發一個action對象
  };

  return (
    <div>
      <button onClick={addList}>add</button>
      <ul>
        {list.map(v => {
          return <li key={v}>{v}</li>;
        })}
      </ul>
    </div>
  );
};

action對象格式爲json對象,並且必須有type屬性否則會報錯誤:Error: Actions may not have an undefined "type" property. Have you misspelled a constant?

攜帶數據一般爲payload屬性,這個沒做強制要求

這樣一個基本的react redux就整合完成了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章