簡易Redux實(shí)現(xiàn)

HTML模板如下

<html>
 <head>
    <title>React App</title>
  </head>
  <body>
    <div id='title'></div>
    <div id='content'></div>
  </body>
</html>

JavaScript代碼如下

function renderApp(newAppState, oldAppState = {}) {
  if (JSON.stringify(oldAppState) === JSON.stringify(newAppState)) return;
  renderTitle(newAppState.title, oldAppState.title)
  renderContent(newAppState.content, oldAppState.content)
}

/**
 * 渲染應(yīng)用標(biāo)題
 * 如果標(biāo)題沒更新,則直接返回,避免重新渲染
 */
function renderTitle(newTitle, oldTitle) {
  if (oldTitle === newTitle) return
  const titleDOM = document.getElementById('title')
  titleDOM.innerHTML = newTitle.text
  titleDOM.style.color = newTitle.color
}

function renderContent(newContent, oldContent) {
  if (oldContent === newContent) return
  const contentDOM = document.getElementById('content')
  contentDOM.innerHTML = newContent.text
  contentDOM.style.color = newContent.color
}

/**
 * 初始化頁面數(shù)據(jù)和修改數(shù)據(jù) 
 */
function stateChanger(state, action){
  if (!state) {
    return {
      title: {
        text: 'React.js 小書',
        color: 'red',
      },
      content: {
        text: 'React.js 小書內(nèi)容',
        color: 'green'
      }
    }
  }
  switch (action.type) {
    case 'UPDATE_TITLE_TEXT':
      return {
        ...state,
        title: {
          ...state.title,
          text: action.text
        }
      }
    case 'UPDATE_TITLE_COLOR':
      return {
        ...state,
        title: {
          ...state.title,
          color: action.color
        }
      }
    case 'UPDATE_CONTENT_TEXT':
      return {
        ...state,
        content: {
          ...state.title,
          text: action.text
        }
      }
    case 'UPDATE_CONTENT_COLOR':
      return {
        ...state,
        content: {
          ...state.title,
          color: action.color
        }
      }
    default:
      return state
  }
}

/**
 * 創(chuàng)建 dispatch,subscribe 和 getState
 */
function createStore(reducer) {
  let state = null
  const Listeners = []
  const subscribe = listener => Listeners.push(listener)  
  const getState = () => state
  const dispatch = action => {
    state = reducer(state, action)
    Listeners.forEach(n => n())
  }
  dispatch({})
  return {
    getState,
    dispatch,
    subscribe
  }
}

const store = createStore(stateChanger)
let oldState = store.getState()

renderApp(oldState)

store.subscribe(() => {
  const newState = store.getState()
  renderApp(newState, oldState)
  oldState = newState
})

setTimeout(()=>{
  store.dispatch({
    type: 'UPDATE_TITLE_TEXT',
    text: '哈哈哈'
  })
  store.dispatch({
    type: 'UPDATE_TITLE_COLOR',
    color: 'blue'
  })
}, 2000)

動(dòng)手實(shí)現(xiàn)Redux

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容