zoukankan      html  css  js  c++  java
  • 关于react-redux中Provider、connect的解析

    Provider

    是什么

    react-redux 提供的一个 React 组件

    作用

    把 store 提供给其子组件

    1. //使用 redux 的 createStore 方法创建的一个 store
    2. const store = createStore(todoApp,{})
    3. // store 作为一个 prop 传给 Provider 组件
    4. render(
    5. <Provider store={store}>
    6. <App/>
    7. </Provider>, document.getElementById('app'))

    connect

    1. connect([mapStateToProps], [mapDispatchToProps], [mergeProps], [options])

    作用

    把“指定的state & 指定的action”和 React组件 连接起来 ==> 容器组件

    参数说明

    mapStateToProps

    这是一个function,返回一个object;

    (state, [ownProps]) => ({ }) // 通常省略第二个参数

    作用 把指定的state作为props注入到 UI组件 中

    1. const mapStateToProps = state => {
    2. return {
    3. title: state.title
    4. list: state.list
    5. };
    6. }

    当然,不必将 state 中的数据原封不动地传入组件,可以根据 state 中的数据,动态地输出组件需要的(最小)属性。

    1. const mapStateToProps = (state) => {
    2. return {
    3. greaterThanFive: state.count > 5 // 假如只需要知道count大不大于5就成
    4. }
    5. }

    函数的第二个参数 ownProps,是 React的UI组件自己的 props。有的时候,ownProps 也会对其产生影响。
    比如,当你在 store 中维护了一个用户列表,而你的组件只关心一个用户。

    1. const mapStateToProps = (state, ownProps) => {
    2. // state 是 {userList: [{id: 0, name: '王二'},{id: 1, name: '李四'}]}
    3. return {
    4. user: _.find(state.userList, {id: ownProps.userId})
    5. }
    6. }
    7. class MyComp extends Component {
    8. static PropTypes = {
    9. userId: PropTypes.string.isRequired,
    10. user: PropTypes.object
    11. };
    12. render(){
    13. return <div>用户名:{this.props.user.name}</div>
    14. }
    15. }
    16. const Comp = connect(mapStateToProps)(MyComp);

    mapDispatchToProps

    这可以是一个function,还可以是object,

    作用 把指定的action作为props注入到UI组件中

    1. // 方法
    2. const mapDispatchToProps = dispatch => {
    3. return {
    4. destroyTodo : () => dispatch({
    5. type : 'DESTROY_TODO'
    6. })
    7. }
    8. }
    9. // 对象

    mergeProps

    是一个函数,用来筛选哪些参数传递给组件。这个函数接受3个参数

    1. const defaultMergeProps = (stateProps, dispatchProps, ownProps ) => ({
    2. ...ownProps,
    3. ...stateProps,
    4. ...dispatchProps
    5. })

    stateProps是mapStateToProps的返回值,dispatchProps是mapDispatchToProps返回值,ownProps 是当前组件自己的属性。
    这个函数默认把这三个返回值拼装到一起传递给组件,可修改。

    options

    一个对象,有两个布尔,一个是pure,一个是withRef。

    • pure为false,只要connect接受到属性,不管是否有变化,必然刷新connect组件。
    • withRef为true时,在装饰传入的 React 组件时,Connect 会保存一个对该组件的 refs 引用,可以通过 getWrappedInstance 方法来获得该 refs,并最终获得原始的 DOM 节点。

    使用

    1. const newApp = connect(store)(UI)
  • 相关阅读:
    解决document.write问题
    js操作css样式
    最强大的对联广告,所有浏览器支持,ie6无抖动,缩放页面ie6没有横向滚动条
    JavaScript绘制图形Canvas
    DDD关键知识点整理汇总
    聚合(根)、实体、值对象精炼思考总结
    DDD领域驱动设计基本理论知识总结
    GVMStart 正常结果
    Ubuntu20.04安装、配置openvas 9
    VS Code MarkDown即时渲染编写插件
  • 原文地址:https://www.cnblogs.com/sameen/p/9182925.html
Copyright © 2011-2022 走看看