Skip to content

Commit

Permalink
Merge pull request #14760 from Hyunly/next
Browse files Browse the repository at this point in the history
Revert(taro-with-weapp):  "把properties转换为React的state,支持可读可写,同时再通过props传入修改后的值"
  • Loading branch information
qican777 authored Nov 3, 2023
2 parents 7cd9965 + cdeef25 commit 31a0734
Showing 1 changed file with 17 additions and 33 deletions.
50 changes: 17 additions & 33 deletions packages/taro-with-weapp/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@ type Observer = (newProps, oldProps, changePath: string) => void

interface ObserverProperties {
name: string
observers: (string | Observer)[]
// observer: string | Observer
observer: string | Observer
}

interface ComponentClass<P = Record<string, any>, S = Record<string, any>> extends ComponentLifecycle<P, S> {
Expand Down Expand Up @@ -40,19 +39,14 @@ function defineGetter (component, key: string, getter: string) {
if (getter === 'props') {
return component.props
}
return component.state
// return {
// ...component.state,
// ...component.props
// }
return {
...component.state,
...component.props
}
}
})
}

function propToState (newValue, _oldValue, key: string) {
this.state[key] = newValue
}

function isFunction (o): o is Func {
return typeof o === 'function'
}
Expand Down Expand Up @@ -130,28 +124,20 @@ export default function withWeapp (weappConf: WxOptions, isApp = false) {
}

private initProps (props: any) {
const properties = {}
for (const propKey in props) {
if (props.hasOwnProperty(propKey)) {
const propValue = props[propKey]
// propValue 可能是 null, 构造函数, 对象
if (propValue && !isFunction(propValue)) {
properties[propKey] = propValue.value
const observers = [propToState]
if (propValue.observer) {
observers.push(propValue.observer)
this._observeProps.push({
name: propKey,
observer: propValue.observer
})
}
this._observeProps.push({
name: propKey,
observers: observers
})
}
}
}
this.state = {
...properties,
...this.state
}
}

private init (options: WxOptions) {
Expand Down Expand Up @@ -389,21 +375,19 @@ export default function withWeapp (weappConf: WxOptions, isApp = false) {
}

private triggerPropertiesObservers (prevProps, nextProps) {
this._observeProps.forEach(({ name: key, observers }) => {
this._observeProps.forEach(({ name: key, observer }) => {
const prop = prevProps?.[key]
const nextProp = nextProps[key]
// 小程序是深比较不同之后才 trigger observer
if (!isEqual(prop, nextProp)) {
observers.forEach((observer)=>{
if (typeof observer === 'string') {
const ob = this[observer]
if (isFunction(ob)) {
ob.call(this, nextProp, prop, key)
}
} else if (isFunction(observer)) {
observer.call(this, nextProp, prop, key)
if (typeof observer === 'string') {
const ob = this[observer]
if (isFunction(ob)) {
ob.call(this, nextProp, prop, key)
}
})
} else if (isFunction(observer)) {
observer.call(this, nextProp, prop, key)
}
}
})
}
Expand Down

0 comments on commit 31a0734

Please sign in to comment.