Provider
是什么
react-redux 提供的一个 React 组件
作用
把 store 提供给其子组件
//使用 redux 的 createStore 方法创建的一个 storeconst store = createStore(todoApp,{})// store 作为一个 prop 传给 Provider 组件render(<Provider store={store}><App/></Provider>, document.getElementById('app'))
connect
connect([mapStateToProps], [mapDispatchToProps], [mergeProps], [options])
作用
把“指定的state & 指定的action”和 React组件 连接起来 ==> 容器组件
参数说明
mapStateToProps
这是一个function,返回一个object;
(state, [ownProps]) => ({ }) // 通常省略第二个参数
作用 把指定的state作为props注入到 UI组件 中
const mapStateToProps = state => {return {title: state.title,list: state.list};}
当然,不必将 state 中的数据原封不动地传入组件,可以根据 state 中的数据,动态地输出组件需要的(最小)属性。
const mapStateToProps = (state) => {return {greaterThanFive: state.count > 5 // 假如只需要知道count大不大于5就成}}
函数的第二个参数 ownProps,是 React的UI组件自己的 props。有的时候,ownProps 也会对其产生影响。
比如,当你在 store 中维护了一个用户列表,而你的组件只关心一个用户。
const mapStateToProps = (state, ownProps) => {// state 是 {userList: [{id: 0, name: '王二'},{id: 1, name: '李四'}]}return {user: _.find(state.userList, {id: ownProps.userId})}}class MyComp extends Component {static PropTypes = {userId: PropTypes.string.isRequired,user: PropTypes.object};render(){return <div>用户名:{this.props.user.name}</div>}}const Comp = connect(mapStateToProps)(MyComp);
mapDispatchToProps
这可以是一个function,还可以是object,
作用 把指定的action作为props注入到UI组件中
// 方法const mapDispatchToProps = dispatch => {return {destroyTodo : () => dispatch({type : 'DESTROY_TODO'})}}// 对象
mergeProps
是一个函数,用来筛选哪些参数传递给组件。这个函数接受3个参数
const defaultMergeProps = (stateProps, dispatchProps, ownProps ) => ({...ownProps,...stateProps,...dispatchProps})
stateProps是mapStateToProps的返回值,dispatchProps是mapDispatchToProps返回值,ownProps 是当前组件自己的属性。
这个函数默认把这三个返回值拼装到一起传递给组件,可修改。
options
一个对象,有两个布尔,一个是pure,一个是withRef。
- pure为false,只要connect接受到属性,不管是否有变化,必然刷新connect组件。
- withRef为true时,在装饰传入的 React 组件时,Connect 会保存一个对该组件的 refs 引用,可以通过 getWrappedInstance 方法来获得该 refs,并最终获得原始的 DOM 节点。
使用
const newApp = connect(store)(UI)