react-redux再探

combineReducers 和 bindActionCreators

在react中用redux的时候,我们通过connect()函数,将原生组件包装成“容器组件”。并且暴露了redux中的State和Dispatch。例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<Provider store={store}>
<App/>
</Provider>

// 定义App组件
class Foo extends React.Component{
render() {
const { text } = this.props;
return <div>{text}</div>;
}
}
const App = connect(
mapStateToProps, #暴露的state为props
mapDispatchToProps # 暴露dispatch为props
)(Foo);

随着我们的state和dispatch中action的增多,子组件的代码变得无法维护,例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
const App = connect(
(state)=>{ #暴露的state为props
return {
state1 : state.counter.state1,
state2 : state.counter.state2,
state3 : state.counter.state3,
state4 : state.counter.state4,
state5 : state.counter.state5,
state6 : state.counter.state6,
state7 : state.counter.state7,
state8 : state.counter.state8,
}
},
(dispatch)=>{ # 暴露dispatch为props
return {
action1 = ()=> dispatch({"type":ACTION1}),
action2 = ()=> dispatch({"type":ACTION2}),
action3 = ()=> dispatch({"type":ACTION3}),
action4 = ()=> dispatch({"type":ACTION4}),
action5 = ()=> dispatch({"type":ACTION5}),
action6 = ()=> dispatch({"type":ACTION6}),
}
}


)(Foo);

这时候就需要combineReducers 和 bindActionCreators登场了。
combineReducers()用来联合多个reducers
bindActionCreators()用来绑定多个action
都是为了方便解构代码。

如何使用combineReducers和bindActionCreators

参考
react-simple

redux-API

结束

emmmm….
肯定还有再再探