Skip to content

Commit

Permalink
fix(transformer): 生成匿名 state也需要带上条件表达式, fix #351
Browse files Browse the repository at this point in the history
  • Loading branch information
yuche committed Jul 20, 2018
1 parent 2b428bd commit 9906c0e
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
18 changes: 18 additions & 0 deletions packages/taro-transformer-wx/__tests__/control-flow.spec.ts
Expand Up @@ -139,5 +139,23 @@ describe('inline 表达式', () => {
const inst = evalClass(ast)
expect(inst.state.anonymousState__temp).toBe(null) // 默认设置为 null
})

test('逻辑表达式', () => {
const { template, ast, code } = transform({
...baseOptions,
isRoot: true,
code: buildComponent(`
const tasks = []
return (
tasks && tasks.length && <View className={\`page\`}>
<Text>Hello world!</Text>
</View>
)
`)
})

const inst = evalClass(ast)
expect(inst.state.anonymousState__temp).toBe(null) // 默认设置为 null
})
})
})
7 changes: 7 additions & 0 deletions packages/taro-transformer-wx/src/utils.ts
Expand Up @@ -27,13 +27,20 @@ export function generateAnonymousState (
const jsx = isLogical ? expression : expression.findParent(p => p.isJSXElement())
const callExpr = jsx.findParent(p => p.isCallExpression() && isArrayMapCallExpression(p)) as NodePath<t.CallExpression>
const conditionExpr = jsx.findParent(p => p.isConditionalExpression())
const logicExpr = jsx.findParent(p => p.isLogicalExpression({ operator: '&&' }))
let expr = cloneDeep(expression.node)
if (conditionExpr && conditionExpr.isConditionalExpression()) {
const consequent = conditionExpr.get('consequent')
if (consequent === jsx || jsx.findParent(p => p === consequent)) {
expr = t.conditionalExpression(conditionExpr.get('test').node as any, expr, t.nullLiteral())
}
}
if (logicExpr && logicExpr.isLogicalExpression({ operator: '&&' })) {
const consequent = logicExpr.get('right')
if (consequent === jsx || jsx.findParent(p => p === consequent)) {
expr = t.conditionalExpression(logicExpr.get('left').node as any, expr, t.nullLiteral())
}
}
if (!callExpr) {
refIds.add(t.identifier(variableName))
statementParent.insertBefore(
Expand Down

0 comments on commit 9906c0e

Please sign in to comment.