首页 > mapStateToProps和mapDispatchToProps的参数问题

mapStateToProps和mapDispatchToProps的参数问题

刚学redux, 不是很明白一下两个function的参数state和dispatch是从哪里来的?求明白人给讲讲!!!

function mapStateToProps(state){
  return {
    counter: state.counter
  }
}

function mapDispatchToProps(dispatch){
  return bindActionCreators(actions, dispatch)
}

connect 传过来的


mapStateToProps(state)中的初始state, 可以在创建store的时候指定一个initialState, 代码:

const initialState = Immutable.fromJS(
    {
      visibilityFilter: "SHOW_ALL",
      todos:[
        {completed: false, text: "12332"},
        {completed: false, text: "321"},
        {completed: true, text: "def"},
        {completed: false, text: "abc"}
      ]
    }
  );
let createStoreWithMiddleware = redux.applyMiddleware(loggerMiddleware)(redux.createStore);
const store = createStoreWithMiddleware(reducers, initialState);

也可以不指定initialState. redux的container组件在执行connect()方法的时候, 会默认调用一个type="@@redux/INIT"的action, 这样的话可以直接在reducer中处理初始state为空的情况, 代码:

function todos(state=initialState.get("todos"), action={}){
  switch (action.type){
    case ADD_TODO:
      const tmp = state.push(Immutable.Map({text:action.text, completed:false}));
      return tmp;
    case COMPLETE_TODO:
      return state.setIn([action.index, "completed"], true);
    default :
      return state
  }
} 
const reducers = {
  visibilityFilter,
  todos
};
module.exports = combineReducers(reducers);

注意: 在使用第一种方法传入initialState时, 如果使用的是Immutable, 默认情况下会报错:The initialState argument passed to createStore has unexpected type of "Object". 修改的办法是安装redux-immutable, 使用redux-immutable创建reducer, 代码:

import {
  combineReducers
} from 'redux-immutable';

const reducers = {
  visibilityFilter,
  todos
};
module.exports = combineReducers(reducers);

木有人回答。。。

【热门文章】
【热门文章】