上节课我们介绍了页面更新与stroe传递的优化,这节课我们来进行最后一个优化项。

回顾

在开始这节课的内容之前我们来对上节课的内容来做一个简单的回顾

  • react-redux自动帮我们监测redux中的状态变化
  • react-redux提供了Provider组件来替我们批量传递store

以上便是我们上节课的主要要点,接下来,我们来开始这节课的内容。

组件结构

我们先来回顾一下我们目前的项目中的文件结构是什么样子?

  • Sum组件
  • Sum UI组件
  • Sum容器组件
  • redux

是不是这样?那么如果我们要上整个项目中有几十个组件要和redux交互,那么我们这不就相当于组件数要翻一倍?因为每个组件都要分开成容器组件和UI组件啊。那么我们有没有什么办法给整合一下呢?

那么我们把这俩组件写在同一个文件里是不是就可以了?

我们来看容器组件中都干了什么?

import SumUI from '../../components/Sum';

export default connect(
  state => ({ sum: state }),
  {
    increment: createIncrementAction,
    decrement: createDecrementAction,
    asyncIncrement: createAsyncIncrementAction
  }
)(SumUI);

我们是不是默认暴露了一个容器组件?这个容器组价里面是不是要用到UI组件?那么UI组件是哪来的?是不是我们手动引入的?除了在容器组件中我们有用到过UI组件吗?是不是没有?所有的对外沟通都是通过容器组件来完成的?那么我们把UI组件和容器组件都写在同一个文件里的话,是不是不需要暴露UI组件了?那么我们改一下

import React, { Component } from 'react'
...

class Sum extends Component {...}

export default connect(
  state => ({ sum: state }),
  {
    increment: createIncrementAction,
    decrement: createDecrementAction,
    asyncIncrement: createAsyncIncrementAction
  }
)(Sum);

我们来看一下,这样的话我们直接在这里定义UI组件,然后再容器组件中直接拿来用是不是就可以了?

优化总结

  • UI组件和容器组件混在一个文件中来编写
  • 使用Provider组件来批量给容器组件传递store
  • react-redux自动监测redux的状态改变
  • mapDispatchToProps可以简写车给一个对象
  • 不再暴露UI组件

Copyright statement:The articles of this site are all original if there is no special explanation, indicate the source please when you reprint.

Link of this article:https://work.lynchow.com/article/ui_and_container_component/