美文网首页
react-redux 中的mapStateToProps, m

react-redux 中的mapStateToProps, m

作者: 牛奶大泡芙 | 来源:发表于2019-03-21 21:07 被阅读0次

mapStateToProps, mapDispatchToProps 查看他们的名称可以看出,react-redux中构造出了state与dispatch,connect中的两个参数就可以将它们引入props

const mapDispatchToProps = {
    action1: ActionCreators.action1
};
function mapStateToProps(state) {
    return {
        state1: state.state1
    };
}
class SubComponent extends React.Component {
 handleClick = () => {
   const { action1 } = this.props; // dispatch
   action1(param);
}
  render(){
  const { state1 } = this.props;
    return (
    <div>{state1}</div> // state from store
    )
  }
}
export connect
   (mapStateToProps, mapDispatchToProps)(SubComponent);

那么jsx外的action和reducer(相当于一个状态机,输入action和state,输出新的state)是如何定义的呢?

function someReduce(state, action){
  switch(action.type) {
    case 'action1':
      return someLogic(action1.data, state); //return a new state
   default:
     break;
  }
}
export default someReducer;

actionCreator

const actionCollect = {
  action1: (param) => (dispatch, getState) => {
    type: 'action1',
    data
  }
}
export default actionCollect;

项目中可能会定义许多reducer,分别处理某一个单一模块的状态机逻辑,reducer整合的逻辑如下

rootReducer = { someReducerName: someReducer};
const rootReducer = function(rootState, action){
  return combinedReducer(rootState, action)
}

相关文章

网友评论

      本文标题:react-redux 中的mapStateToProps, m

      本文链接:https://www.haomeiwen.com/subject/porhvqtx.html