간편한 Redux 구현

2799 단어
HTML 템플릿은 다음과 같습니다.

 
    React App
  
  
    

JavaScript代码如下

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

/**
 *       
 *        ,     ,      
 */
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
}

/**
 *              
 */
function stateChanger(state, action){
  if (!state) {
    return {
      title: {
        text: 'React.js   ',
        color: 'red',
      },
      content: {
        text: 'React.js     ',
        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
  }
}

/**
 *    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)

Redux 구축

좋은 웹페이지 즐겨찾기