Skip to content

Commit

Permalink
feat(cli h5 redux-h5 router): h5路由的一些改动
Browse files Browse the repository at this point in the history
- 增加了Taro.getApp
- 调整了内部路由参数的传递方式
- 调整了componentDidShow、componentDidHide的实现
- 修复后退两次报错的问题
- 更新router包的依赖
- taro-h5类型文件更新
  • Loading branch information
Littly committed Dec 11, 2018
1 parent 22b2005 commit 57e6e5f
Show file tree
Hide file tree
Showing 12 changed files with 176 additions and 235 deletions.
17 changes: 16 additions & 1 deletion packages/taro-cli/src/h5.js
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ function processEntry (code, filePath) {
let renderCallCode

let hasAddNervJsImportDefaultName = false
let hasConstructor = false
let hasComponentWillMount = false
let hasComponentDidMount = false
let hasComponentDidShow = false
Expand All @@ -121,6 +122,7 @@ function processEntry (code, filePath) {
let hasState = false

const initPxTransformNode = toAst(`Taro.initPxTransform(${JSON.stringify(pxTransformConfig)})`)
const additionalConstructorNode = toAst(`Taro._set$app(this)`)

ast = babel.transformFromAst(ast, '', {
plugins: [
Expand Down Expand Up @@ -181,6 +183,7 @@ function processEntry (code, filePath) {
const isComponentWillMount = keyName === 'componentWillMount'
const isComponentDidMount = keyName === 'componentDidMount'
const isComponentWillUnmount = keyName === 'componentWillUnmount'
const isConstructor = keyName === 'constructor'

if (isRender) {
const routes = pages.map((v, k) => {
Expand Down Expand Up @@ -256,11 +259,16 @@ function processEntry (code, filePath) {
/* 插入<Router /> */
node.body = toAst(`{return (${funcBody});}`, { preserveComments: true })
}

if (tabBar && isComponentWillMount) {
const initTabBarApisCallNode = toAst(`Taro.initTabBarApis(this, Taro)`)
astPath.get('body').pushContainer('body', initTabBarApisCallNode)
}

if (hasConstructor && isConstructor) {
astPath.get('body').pushContainer('body', additionalConstructorNode)
}

if (hasComponentDidShow && isComponentDidMount) {
const componentDidShowCallNode = toAst(`this.componentDidShow()`)
astPath.get('body').pushContainer('body', componentDidShowCallNode)
Expand Down Expand Up @@ -296,6 +304,11 @@ function processEntry (code, filePath) {
'method', t.identifier('componentWillUnmount'), [],
t.blockStatement([]), false, false))
}
if (!hasConstructor) {
astPath.pushContainer('body', t.classMethod(
'method', t.identifier('constructor'), [t.identifier('props'), t.identifier('context')],
t.blockStatement([toAst('super(props, context)'), additionalConstructorNode]), false, false))
}
if (tabBar) {
if (!hasComponentWillMount) {
astPath.pushContainer('body', t.classMethod(
Expand Down Expand Up @@ -475,7 +488,9 @@ function processEntry (code, filePath) {
const node = astPath.node
const key = node.key
const keyName = getObjKey(key)
if (keyName === 'componentWillMount') {
if (keyName === 'constructor') {
hasConstructor = true
} else if (keyName === 'componentWillMount') {
hasComponentWillMount = true
} else if (keyName === 'componentDidMount') {
hasComponentDidMount = true
Expand Down
14 changes: 10 additions & 4 deletions packages/taro-components/src/components/tabbar/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,17 @@ class Tabbar extends Nerv.Component {
}

getCurrentPathname () {
const pathname = this.props.mode === 'hash'
? location.hash
: location.pathname
let pathname
let publicPath
if (this.props.mode === 'hash') {
pathname = location.hash
publicPath = ''
} else {
pathname = location.pathname
publicPath = this.props.publicPath
}

return pathname ? pathname.replace(new RegExp(`^#?${this.props.publicPath}/?`), '') : this.homePage
return pathname.replace(/\?[\s\S]*$/, '').replace(new RegExp(`^#?${publicPath}/?`), '')
}

hashChangeHandler ({ toLocation } = {}) {
Expand Down
23 changes: 3 additions & 20 deletions packages/taro-h5/src/component.js
Original file line number Diff line number Diff line change
@@ -1,38 +1,21 @@
import Nerv from 'nervjs'
import Taro from './index'

class Component extends Nerv.Component {
get $router () {
if (this.context && this.context.router) {
return this.context.router.location
}
return Taro.getRouter()
}
set $router (args) {
console.warn('Property "$router" is read-only.')
}

get $app () {
if (!this.vnode) return {}
if (!this._$app) this._$app = getApp(this)
return this._$app
return Taro.getApp()
}

set $app (app) {
console.warn('Property "$app" is read-only.')
}
}

/**
* 往上遍历直到找到根节点
* @param {Nerv Component} component 当前的组件实例
* @return {Nerv Component} 根节点实例
*/
function getApp (component) {
const vnode = component.vnode

if (!vnode) return {}
if (vnode._owner) return getApp(vnode._owner)

return component
}

export default Component
10 changes: 10 additions & 0 deletions packages/taro-h5/src/native-api.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,16 @@ export default function initNativeApi (taro) {
taro.requirePlugin = function () {
console.error('不支持 API requirePlugin')
}
taro._set$app = function (app) {
taro._$app = app
}
taro.getApp = () => taro._$app

taro._set$router = function (router) {
taro._$router = router
}
taro.getRouter = () => taro._$router

taro.canIUseWebp = canIUseWebp
Object.assign(taro, storage, interactive, webSocket, tabBar, system, navigationBar, imageUtils, others)
}
19 changes: 19 additions & 0 deletions packages/taro-h5/types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10246,4 +10246,23 @@ declare namespace TaroH5 {

/* initNativeApi */
function initNativeApi(any): void

function _set$app(any): void;
function getApp(): any;
function _set$router(any): void;

namespace Router {
export interface Location {
pathname: string;
search: string;
hash: string;
state: {
key: string;
};
params: {
[key: string]: string;
};
}
}
function getRouter(): Router.Location;
}
75 changes: 28 additions & 47 deletions packages/taro-redux-h5/react-redux/components/connectAdvanced.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,20 @@ import invariant from 'invariant'
import { Component, createElement } from '../../src/compat'
import Subscription from '../utils/Subscription'
import { storeShape, subscriptionShape } from '../utils/PropTypes'
import { tryToCall } from '../utils/tryToCall'

/* eslint-disable react/no-deprecated */

const getRoute = (component) => {
const vnode = component.vnode

if (component.isRoute) return component
if (!vnode) return {}
if (vnode._owner) return getRoute(vnode._owner)

return component
}

let hotReloadingVersion = 0
const dummyState = {}
function noop() {}
Expand All @@ -20,14 +31,12 @@ function makeSelectorStateful(sourceSelector, store) {

/**
* 如果是页面 根据目前&未来展示状态判断是否需要update
* 通过 selector.shouldComponentUpdate = false 阻止更新
*/
if (props.__router) {
const lastShouldShow = ctx.props.__router.state === ctx.locationState
const nextShouldShow = props.__router.state === ctx.locationState
const canReceiveProps = lastShouldShow || nextShouldShow
if (!canReceiveProps) {
selector.shouldComponentUpdate = false
}

const route = getRoute(ctx)
if (!route.matched) {
selector.shouldComponentUpdate = false
}
selector.props = nextProps
selector.error = null
Expand Down Expand Up @@ -145,6 +154,10 @@ export default function connectAdvanced(
this.initSubscription()
}

get config () {
return this.wrappedInstance ? this.wrappedInstance.config : {}
}

getChildContext() {
// If this component received store from props, its subscription should be transparent
// to any descendants receiving store+subscription from context; it passes along
Expand All @@ -168,6 +181,10 @@ export default function connectAdvanced(
if (this.selector.shouldComponentUpdate) this.forceUpdate()
}

componentDidShow () {
tryToCall(this.wrappedInstance.componentDidShow, this.wrappedInstance)
}

componentWillReceiveProps(nextProps) {
this.selector.run(nextProps, { ctx: this })
}
Expand All @@ -185,6 +202,10 @@ export default function connectAdvanced(
this.selector.shouldComponentUpdate = false
}

componentDidHide() {
tryToCall(this.wrappedInstance.componentDidHide, this.wrappedInstance)
}

getWrappedInstance() {
invariant(withRef,
`To access the wrapped instance, you need to specify ` +
Expand Down Expand Up @@ -278,46 +299,6 @@ export default function connectAdvanced(
Connect.contextTypes = contextTypes
Connect.propTypes = contextTypes

// const componentDidShow = WrappedComponent.prototype.componentDidShow
// const componentDidHide = WrappedComponent.prototype.componentDidHide
// const originalComponentDidMount = WrappedComponent.prototype.componentDidMount
// const originalComponentWillUnmount = WrappedComponent.prototype.componentWillUnmount
// const originalConnectComponentDidMount = Connect.prototype.componentDidMount
// const originalConnectComponentWillUnmount = Connect.prototype.componentWillUnmount

/**
* 调用过程
*
* Connect.prototype.componentDidMount
* Connect.prototype.componentDidShow [router调用]
* WrappedComponent.prototype.componentDidMount = didMount + didShow
* WrappedComponent.prototype.compomentDidShow [只有didMount用]
*/

// WrappedComponent.prototype.componentDidMount = function () {
// originalComponentDidMount && originalComponentDidMount.call(this)
// componentDidShow && componentDidShow.call(this)
// }
// WrappedComponent.prototype.componentWillUnmount = function () {
// componentDidHide && componentDidHide.call(this)
// originalComponentWillUnmount && originalComponentWillUnmount.call(this)
// }

// Connect.prototype.componentDidMount = function () {
// originalConnectComponentDidMount.call(this)
// this.componentDidShow = function () {
// const comp = this.wrappedInstance
// componentDidShow && componentDidShow.call(comp)
// }
// }
// Connect.prototype.componentWillUnmount = function () {
// originalConnectComponentWillUnmount.call(this)
// this.componentDidHide = function () {
// const comp = this.wrappedInstance
// componentDidHide && componentDidHide.call(comp)
// }
// }

if (process.env.NODE_ENV !== 'production') {
Connect.prototype.componentWillUpdate = function componentWillUpdate() {
// We are hot reloading!
Expand Down
16 changes: 16 additions & 0 deletions packages/taro-redux-h5/react-redux/utils/tryToCall.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/**
* 尝试调用函数
*
* @param {function} func 调用的函数
* @param {any} ctx 调用上下文
* @param {...any} args 函数调用参数
* @returns {any} returnValue
*/
export const tryToCall = (func, ctx = null, ...args) => {
if (!func) return
if (ctx) {
return func.apply(ctx, args)
} else {
return func(...args)
}
}
3 changes: 2 additions & 1 deletion packages/taro-router/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
"license": "MIT",
"dependencies": {
"invariant": "^2.2.4",
"lodash": "^4.17.11",
"resolve-pathname": "^2.2.0",
"rollup-plugin-alias": "^1.4.0",
"value-equal": "^0.4.0",
Expand All @@ -39,7 +40,7 @@
"@babel/plugin-syntax-dynamic-import": "^7.0.0",
"@babel/plugin-transform-react-jsx": "^7.0.0",
"@babel/preset-env": "^7.1.5",
"@tarojs/taro-h5": "^1.1.0-beta.8",
"@tarojs/taro-h5": "^1.2.0-beta.13",
"@types/history": "^4.7.2",
"@types/jasmine": "^2.8.11",
"@types/jest": "^23.3.9",
Expand Down
2 changes: 2 additions & 0 deletions packages/taro-router/src/history/createHistory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ const createHistory = (props: { basename?: string, mode: "hash" | "browser" } =

const initialLocation = getDOMLocation(initState)
let lastLocation = initialLocation
Taro._set$router(initialLocation)

let store = tryToParseStore(initState)

Expand Down Expand Up @@ -129,6 +130,7 @@ const createHistory = (props: { basename?: string, mode: "hash" | "browser" } =
action: history.action
}

Taro._set$router(history.location)
Taro['eventCenter'].trigger('routerChange', {...params})
transitionManager.notifyListeners({...params})
}
Expand Down
Loading

0 comments on commit 57e6e5f

Please sign in to comment.