Better

Ethan的博客,欢迎访问交流

了解到一个 React 脚手架 Rekit

Rekit 相比 create-react-app 而言,定位的是企业级别的脚手架,不仅针对常用的库做了集成,项目结构也做了规定。

对比 create-react-app

对比 create-react-app 和 Rekit

  • Rekit 默认没开启 CSS Modules 功能
  • Rekit 对热更新做了很好的集成
  • 路由数据使用 react-router-redux 集中管理
  • 按照领域模型组织代码。style、route、component、store 分散在各个 feature 中,每个 feature 中善用 index.xxx 集中导出
  • 每个 feature 中 store 的 action 和 reducer 又按照功能进行了细分
  • 路由进行中心配置化管理,在 v4 版本中废弃的东西,又捡回来,是否合适呢?

create-react-app 对于 Styles 的支持还是很全面的

  • 内置支持 CSS Modules
  • 支持 Sass 等预处理器,安装即可
  • 支持 Autoprefixer 等后置处理器,在 package.json 指定目标浏览器即可

create-react-app 从 2.0 版本开始内置支持 CSS Modules

  • 局部样式:xxx.module.css
  • 全局样式:xxx.css

Rekit 启发

react-reduxconnect 的两个参数,建议使用具名函数来表示,会容易理解一些,具体如下

  • mapStateToProps(state)
  • mapDispatchToProps(dispatch)

对于 mapDispatchToProps 如果要处理多个 action,可以考虑使用 bindActionCreators 辅助函数,该函数功能简单,核心代码代码如下

function bindActionCreator(actionCreator, dispatch) {
  return function() { return dispatch(actionCreator.apply(this, arguments)) }
}
export default function bindActionCreators(actionCreators, dispatch) {
  if (typeof actionCreators === 'function') {
    return bindActionCreator(actionCreators, dispatch)
  }
  const keys = Object.keys(actionCreators)
  const boundActionCreators = {}
  for (let i = 0; i < keys.length; i++) {
    const key = keys[i]
    const actionCreator = actionCreators[key]
    if (typeof actionCreator === 'function') {
      // 进行绑定
      boundActionCreators[key] = bindActionCreator(actionCreator, dispatch)
    }
  }
  return boundActionCreators
}

路由权限控制

  • 提供一个 AuthorizedRoute 组件
  • 中心化路由配置
    • 在路由 JSON 配置中,添加标志位,比如 protected 或者 role
    • 解析 JSON 的时候,根据登录信息和 protected,对路由配置的 component 和 childRoutes 进行修改即可

AuthorizedRoute 组件参考

import React from 'react'
import { Route, Redirect } from 'react-router-dom'
import { setLoginRedirectUrl } from '../actions/loginAction'

class AuthorizedRoute extends React.Component {
  render() {
    const { component: Component, ...rest } = this.props
    const isLogged = sessionStorage.getItem("userName") != null ? true : false;
    if(!isLogged) {
      setLoginRedirectUrl(this.props.location.pathname);
    }
    return (
        <Route {...rest} render={props => {
          return isLogged
              ? <Component {...props} />
              : <Redirect to="/login" />
        }} />
    )
  }
}
export default AuthorizedRoute

react-router 版本

react-router vs react-router-dom vs history

  • v4 取消了中心化配置路由,静态路由变成了动态路由,v4 只需要引入 react-router-dom,会同时安装 history
  • react-router-dom 基于 react-router,并加入了在浏览器运行环境下的一些功能。
  • 只需要安装相应环境下的库即可,不用再显式安装react-router。基于浏览器环境的开发,只需要安装react-router-dom;基于react-native环境的开发,只需要安装react-router-native

项目结构

该思考之处



留言