react笔记2-React-Redux

Redux就比较麻烦了, 为了明确分工, 分出了好几种概念
React-Redux就更麻烦了, 看了好几遍规范 还是记不住哪块是干嘛的…

一.Redux

先说Redux

一.1 Store

Store 就是保存数据的地方,你可以把它看成一个容器。整个应用只能有一个 Store。
createStore是Redux的API, 传参是Reducer

1
2
//传入参数是个Reducer
const store = createStore(counter);

如果想拿到React的state, 就得通过store

1
const state = store.getState();

一.2 Action

State 的变化,会导致 View 的变化。但是,用户接触不到 State,只能接触到 View。
所以,State 的变化必须是 View 导致的。Action 就是 View 发出的通知,表示 State 应该要发生变化了。

1
2
//声明一种Action(type属性是必须的)
const increaseAction = {type: 'increase'};

一.3 Reducer

Store 收到 Action 以后,必须给出一个新的 State,这样 View 才会发生变化。这种 State 的计算过程就叫做 Reducer。
Reducer 是一个函数,它接受 Action 和当前 State 作为参数,返回一个新的 State。

1
2
3
4
5
6
7
8
9
function counter(state = {count: 0}, action) {
const count = state.count;
switch (action.type) {
case 'increase':
return {count: count + 1};
default:
return state
}
}

二.React-Redux

React-Redux要求分为UI组件 和 容器组件

UI组件负责UI的呈现,容器组件负责管理数据和逻辑。
你可能会问,如果一个组件既有UI又有业务逻辑,
就要将它拆分成下面的结构:外面是一个容器组件,里面包了一个UI组件。
前者负责与外部的通信,将数据传给后者,由后者渲染出视图。

二.1 UI组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// React component
class Counter extends React.Component {
render() {
const {value, onIncreaseClick} = this.props;
return (
<div>
<span>{value}</span>
<button onClick={onIncreaseClick}>Increase</button>
</div>
)
}
}
// React提供的校验API
Counter.propTypes = {
value: React.PropTypes.number.isRequired,
onIncreaseClick: React.PropTypes.func.isRequired
};

二.2 容器组件

React-Redux 提供connect方法,用于从 UI 组件生成容器组件。connect的意思,就是将这两种组件连起来。

1
2
3
4
5
//Connected Component
const App = connect(
mapStateToProps,//负责输入逻辑(将state映射到 UI 组件的参数(props))
mapDispatchToProps//后者负责输出逻辑,即将用户对 UI 组件的操作映射成 Action
)(Counter);//Counter是上述的UI组件

二.3 mapStateToProps

它的作用就是像它的名字那样,建立一个从(外部的)state对象到(UI 组件的)props对象的映射关系。

1
2
3
4
5
6
// Map Redux state to component props
function mapStateToProps(state) {
return {
value: state.count
}
}

mapStateToProps会订阅 Store,每当state更新的时候,就会自动执行,重新计算 UI 组件的参数,从而触发 UI 组件的重新渲染

二.4 mapDispatchToProps

用来建立 UI 组件的参数到store.dispatch方法的映射。也就是说,它定义了哪些用户的操作应该当作 Action,传给 Store

1
2
3
4
5
6
// Map Redux actions to component props
function mapDispatchToProps(dispatch) {
return {
onIncreaseClick: () => dispatch(increaseAction)
}
}

定义了 UI 组件的参数怎样发出 Action。返回的 Action 会由 Redux 自动发出

二.5 组件

为组件提供store和state

1
2
3
4
5
6
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);