iT邦幫忙

2021 iThome 鐵人賽

DAY 19
0
Modern Web

Web Component 網頁元件之路系列 第 19

[Day19] - MyRedux 手動製作簡易版 Redux

利用 Redux 當 React Component 中的資料發生變化時 , 告知 Vue Component 資料發生變化


make a proxy as redux store ( no middleware )

custom it , to make it as redux store

const createStore = (reducer /*, middleware */) => {

  const state = {};

  const store = {
    getState: () => state,
    dispatch: action => reducer(state, action)
  };

  return store;
}

// actionType
const ADD_TODO = 'ADD_TODO';

// action
const boundAddTodo = (text) => dispatch(addTodo(text))

function addTodo(text) {
  return {
    type: ADD_TODO,
    text
  }
}

// reducer 
const initialState = {
  todos: []
}

function todoApp(state = initialState, action) {
  switch (action.type) {
    case ADD_TODO:
      return {
        todos: [
          ...state.todos,
          {text: action.text}
        ]
      }
    default:
      return state
  }
}

const store = createStore(todoApp);

// 記錄初始 state
console.log(store.getState())

// Dispatch 一些 action
store.dispatch(addTodo('Learn about actions'))
store.dispatch(addTodo('Learn about reducers'))

console.log(store.getState())

store.dispatch(addTodo('Learn about store'))

console.log(store.getState())
const mapStateToProps = (state) => {
  return {
    todos: state.todos
  };
};

const mapDispatchToProps = dispatch => {
  return {
    goToHome: () => dispatch(push('/')),
  };
};

// the using of react , use the HOC 
// make the connect function as a HOC
connect(mapStateToProps, mapDispatchToProps)(Component);

上一篇
[Day18] - 打包 Element-UI 的 Vue Component to Web Component
下一篇
[Day20] - 串接 React Component 與 Vue Component 的 DATA
系列文
Web Component 網頁元件之路30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言