JS的状态管理框架

1.Redux: Single Source of Truth

2.1.Redux: 可预测性

2.2.state + action = new state

2.3纯函数更新Store

深入理解Store,Action,Reducer

理解store

const store = create(reducer)
1.getState()
2.dispatch(action)
3.subscribe(listener)

理解action

{
  type: ADD_TODO,
  text: 'Build my first Redux app'
}

理解reducer

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

Redux

Redux.gif

Redux组成部件

1.Store

2.Actions

3.Reducer

4.View

理解combineReducers

1.
export default function todos(state = [],action) {
  switch(action.type) {
    case 'ADD_TODO':
      return state.concat([action.text])
    default:
      return state
  }
}
2.
export default function counter(state = 0,action) {
  switch(action.type) {
    case 'INCREMENT':
      return state + 1
    case 'DECREMENT':
      return state - 1
    default:
      return state
  }
}
结合1和2

import {combineReducers} from 'redux'
import todos from './todos'
import counter from './counter'
export default combineReducers({
  todos,
  counter
})

理解bindActionCreators

1.
function addTodoWithDispatch(text) {
  const action = {
    type: ADD_TODO,
    text
  }
  dispatch(action)
}
2.
dispatch(addTodo(text))
dispatch(completeTodo(index))
3.
const boundAddTodo = text => dispatch(addTodo(text))
const boundCompleteTodo = index => dispatch(completeTodo(index))
4结合那些函数
function bindActionCreators(actionCreator,dispatch) {
  return function() {
    return dispatch(actionCreator.apply(this,arguments))
  }
}
function bindActionCreators(actionCreators,dispatch) {
  const keys = Object.keys(actionCreators)
  const boundActionCreators = {}
  for (let i = 0; i < keys.length;i++) {
    const key = keys[i]
    const actionCreator = actionCreators[key]
    if(typeof actionCreator === 'function') {
      boundActionCreators[key] = bindActionCreator(actionCreator,dispatch)
    }
  }
  return boundActionCreators
}

在React中使用Redux

1.记数为例
const initialState = {count: 0};

const counter = (state = initialSate,action) => {
  switch (action.type) {
    case "PLUS_ONE":
      return {count: state.count + 1};
    case "MINUS_ONE":
      return {count: state.count - 1};
    case "CUSTOM__COUNT":
      return {count:state.count + action.payload.count};
    default:
      break;
  }
  return state;
};


//Creator store
const store = createStore(counter);


//Action creator
function plusOne() {
  return {type:"PLUS_ONE"};
}
function minusOne() {
  return {type:"MINUS_ONE"};
}
export class Counter extends React.Component {
  render() {
    const {count,plusOne,minusOne} = this.props;
    return 
  }
}