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)
}
网友评论