redux

redux

action,containers和reducer

  • action 主要是数据从应用传到store

    1
    store.dispatch(action)
  • containers是组件

  • 与component 不同 component主要是负责UI的展示
  • containers 主要是负责逻辑
  • reducer 是用来更新state
    1
    const store = createStore(reducer)

API

  • combineReducers
  • 将多个reducer 合成一个
    1
    const reducer = combineReducers({reducer1,reducer2})
  • connect (react-redux)
  • 将包装好的组件连接到Redux
    1
    connect()(Component)
1
connect(mapStateToProps,mapDispatchToProps)(Component)

FUNCTION

  • mapStateToProps
  • 建立一个从(外部的)state对象到(UI 组件的)props对象的映射关系
  • 会接受state
  • 返回一个对象
    1
    2
    3
    4
    5
    6
    const mapStateToProps = (state) => {
    return {
    // 过滤显示的内容
    todos: getVisibleTodos(state.todos, state.visibilityFilter)
    }
    }
  • mapDispatchToProps
  • 可以是一个函数也可以是一个对象
  • 用来建立 UI 组件的参数到store.dispatch方法的映射
  • 会接受dispacth和ownProps
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    // function
    const mapDispatchToProps = (
    dispatch,
    ownProps
    ) => {
    return {
    onClick: () => {
    dispatch({
    type: 'SET_VISIBILITY_FILTER',
    filter: ownProps.filter
    });
    }
    };
    }
1
2
3
const mapDispatchToProps = {
onClick: VALUE
}

===> component=>actionCreator=>reducer=>component