首先 Redux和react-redux不是一个东西。
- Redux是一个有用的架构,它用来管理状态。我们可以在react\vue\jquery项目里运用它。文档地址
- react-redux是Redux作者专门为react封装的库,它在react项目中提供了便利,但是需要掌握额外的API
UI组件
class Counter extends Component {
render() {
const { value, onIncreaseClick } = this.props
return (
<div>
<span>{value}</span>
<button onClick={onIncreaseClick}>Increase</button>
</div>
)
}
}
使用react-redux之前需要先了解几个js之间的关系
stroe.js
action.js
Reducer.js
store
store是保存数据的地方,整个应用只能有一个store。
store对象包含所以数据,通过store.getState()
可以拿到当前时刻的state,一个state对应一个view。这里的state可以理解成vuex里的state,当state变化的时候view跟着变化
Redux 提供createStore这个函数,用来生成 store。createStore函数接受另一个函数作为参数,返回新生成的 store 对象,这个函数参数可以是reducer方法,这样dispatch方法就会触发reducer自动执行
import { createStore } from 'redux';
import counter from './Reducer'
const store = createStore(counter);
const state = store.getState();
action
action 就是 View 发出的通知,表示 State 应该要发生变化了。action 是一个对象。其中的type属性是必须的,表示 action 的名称,其他属性可以自由设置。action的作用相当于一段信息,它告诉state,’view的xxx发生了变化’,但具体变化的方法需要由reducer执行,action 描述当前发生的事情
const increaseAction = { type: 'increase' }
如何发送action呢?
在redux里,当view发生action以后,通过store.dispatch()
发送
react-redux提供了connect方法,这个方法接收2个参数,mapStateToProps
mapDispatchToProps
const App = connect(
mapStateToProps,
mapDispatchToProps
)(Counter)
mapStateToProps
它是一个函数,它接受state作为参数,返回的是一个对象,对象的key是组件的参数(prop),值映射的是state的值
function mapStateToProps(state) {
return {
value: state.count
}
}
}
mapStateToProps会订阅 Store,每当state更新的时候,就会自动执行,重新计算 UI 组件的参数,从而触发 UI 组件的重新渲染。
mapStateToProps的第一个参数总是state对象,还可以使用第二个参数,代表容器组件的props对象。
mapDispatchToProps
mapDispatchToProps是connect函数的第二个参数,用来建立 UI 组件的参数到store.dispatch方法的映射。也就是说,它定义了哪些用户的操作应该当作 Action,传给 Store。它可以是一个函数,也可以是一个对象。
如果mapDispatchToProps是一个函数,会得到dispatch和ownProps(容器组件的props对象)两个参数。
function mapDispatchToProps(dispatch) {
return {
onIncreaseClick: () => dispatch(increaseAction)
}
}
reducer
store 收到 action 以后,必须给出一个新的 State,这样 View 才会发生变化。这种 state 的计算过程就叫做 reducer。
function counter(state = { count: 0 }, action) {
const count = state.count
switch (action.type) {
case 'increase':
return { count: count + 1 }
default:
return state
}
}
这种state的计算过程就叫做reducer