mopduan/team

Preact关于router和redux迁移指南

Opened this issue · 0 comments

背景

近期团队对部门系列产品进行一系列的性能优化,前端整体框架由React迁移至Preact,在项目中使用了redux + router开发了一部分页面,需要使用Preact来实现相同的功能。

Redux

Redux可以继续使用,但是React Redux需要相应的替换为Preact Redux,将其通过script标签引入,原来代码中的

import { Provider, connect } from 'react-redux';

需要替换为

import { Provider, connect } from 'preact-redux';

Router

原来使用的是React Router 3,想要兼容Preact需要引入preact-compat依赖,但是React Router 4完美兼容Preact,但是API有所变动,详细阅读新版本的文档之后,新版本的React Router提供的React Router DOM库,而且提供高阶组件HashRouter,迁移成本较小。

React Router替换事项:

  1. Router下只有一个Children
<Router>
    <div>
        <Route path="/" component={App}/>
    </div>
</Router>

  1. this.props.location.query被废弃,使用this.props.location.search,search类似window.location.search,是一个字符串,取出值需要自行解析, publishUtils详见ld/mobile/pulish/common/:
import { parseSearch } from '../common/publishUtils';
...
let { cid, qid } = parseSearch(this.props.location.search);
  1. 不再使用Router + hashHistory,使用React Router DOM提供的高阶组件HashRouter:
<HashRouter>
    <div>
        <Route path="/" component={App}/>
    </div>
</HashRouter>
  1. 组件中不再使用hashHistory进行路由跳转,React Router DOM会将push方法set进入组件的props中,改为使用this.props.push:
let { push } = this.props;
...
<div onClick={() => push('/path/of/route')}/>
  1. 使用Preact时,多次切换路由会触发多次componentDidMount事件,从而在该方法中进行的点击事件绑定会绑定多次,React则不会;路由切换时不会触发componentWillUnmount事件。(有待进一步确认,目前观察的情况是这样)

组件

connect方法改为从preact-redux中引入:

import { connect } from 'preact-redux';

剩余只需要按照 #2 进行改动即可。