父組件javascript
class Index extends Component { static childContextTypes = { themeColor: PropTypes.string } constructor () { super() this.state = { themeColor: 'red' } } getChildContext () { return { themeColor: this.state.themeColor } } render () { return ( <div> <Header /> <Main /> </div> ) } }
子組件java
class Title extends Component { static contextTypes = { themeColor: PropTypes.string } render () { return ( <h1 style={{ color: this.context.themeColor }}>React.js 小書標題</h1> ) } }
數據statereact
let appState = { title: { text: 'React.js 小書', color: 'red', }, content: { text: 'React.js 小書內容', color: 'blue' } }
function dispatch (action) { switch (action.type) { case 'UPDATE_TITLE_TEXT': appState.title.text = action.text break case 'UPDATE_TITLE_COLOR': appState.title.color = action.color break default: break } }
根據action對象,預設了type和響應的處理redux
dispatch == stateChanger+listenerActionapp
function createStore (state, stateChanger) { const getState = () => state const dispatch = (action) => stateChanger(state, action) return { getState, dispatch } }
function createStore (state, stateChanger) { const listeners = [] const subscribe = (listener) => listeners.push(listener) const getState = () => state const dispatch = (action) => { stateChanger(state, action) listeners.forEach((listener) => listener()) } return { getState, dispatch, subscribe } }
修改stateChanger,返回新狀態less
function stateChanger (state, action) { 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 } } default: return state // 沒有修改,返回原來的對象 } }
function stateChanger (state, action) { if (!state) { return { title: { text: 'React.js 小書', color: 'red', }, content: { text: 'React.js 小書內容', color: 'blue' } } } 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 } } default: return state } }
function createStore (stateChanger) { let state = null const listeners = [] const subscribe = (listener) => listeners.push(listener) const getState = () => state const dispatch = (action) => { state = stateChanger(state, action) listeners.forEach((listener) => listener()) } dispatch({}) // 初始化 state return { getState, dispatch, subscribe } }
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((listener) => listener()) } dispatch({}) // 初始化 state return { getState, dispatch, subscribe } }
本文是《React.js 小書》的一些筆記,梳理redux中的一些概念
文中代碼源自 鬍子大哈 的《React.js 小書》性能