javascript - mapStateToProps和mapDispatchToProps的参数问题
阿神
阿神 2017-04-11 09:10:06
[JavaScript讨论组]

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

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

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

闭关修行中......

全部回复(3)
PHP中文网

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);
大家讲道理

木有人回答。。。

大家讲道理

connect 传过来的

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号