Skip to content

Commit

Permalink
refactor(weapp): 两新生命周期有任一存在,就不会调用旧生命周期
Browse files Browse the repository at this point in the history
  • Loading branch information
yuche committed Jun 4, 2019
1 parent 95f9a6f commit 896ae85
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 3 deletions.
4 changes: 3 additions & 1 deletion docs/apis/about/tarocomponent.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,14 +80,16 @@ class Welcome extends Component {
constructor(props)
```

React 组件的构造函数将会在装配之前被调用。当为一个 `Taro.Component` 子类定义构造函数时,你应该在任何其他的表达式之前调用 `super(props)`。否则,this.props 在构造函数中将是未定义,并可能引发异常。
Taro 组件的构造函数将会在装配之前被调用。当为一个 `Taro.Component` 子类定义构造函数时,你应该在任何其他的表达式之前调用 `super(props)`。否则,this.props 在构造函数中将是未定义,并可能引发异常。

构造函数是初始化状态的合适位置。若你不初始化状态且不绑定方法,那你也不需要为你的 Taro 组件定义一个构造函数。

> 在 Taro 中,即便你不写 constructor(),编译到微信小程序时也会自动给你加上,因为 Taro 运行时框架需要在 constructor() 中多做一些事情。

可以基于属性来初始化状态。这样有效地“分离(forks)”属性并根据初始属性设置状态。

###

### componentWillMount()

```jsx
Expand Down
8 changes: 6 additions & 2 deletions packages/taro-weapp/src/lifecycle.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ import { enqueueRender } from './render-queue'
// process.env.NODE_ENV !== 'production'

function hasNewLifecycle (component) {
return isFunction(component.constructor.getDerivedStateFromProps)
const { getDerivedStateFromProps, getSnapshotBeforeUpdate } = component.constructor
return isFunction(getDerivedStateFromProps) || isFunction(getSnapshotBeforeUpdate)
}

function callGetDerivedStateFromProps (component, props, state) {
Expand Down Expand Up @@ -145,7 +146,6 @@ function doUpdate (component, prevProps, prevState) {
Current.current = null
}
}
const snapshot = callGetSnapshotBeforeUpdate(component, prevProps, prevState)

data = Object.assign({}, props, data)
if (component.$usedState && component.$usedState.length) {
Expand All @@ -171,6 +171,10 @@ function doUpdate (component, prevProps, prevState) {

const dataDiff = diffObjToPath(data, component.$scope.data)
const __mounted = component.__mounted
let snapshot
if (__mounted) {
snapshot = callGetSnapshotBeforeUpdate(component, prevProps, prevState)
}

// 每次 setData 都独立生成一个 callback 数组
let cbs = []
Expand Down

0 comments on commit 896ae85

Please sign in to comment.