Skip to content

多重map中使用临时变量与三元表达式,编译结果错误 #2814

Closed
@imageslr

Description

多层map的情况下,当里层map引用外层map的变量时,编译过程中的临时变量$loopState__tempX编译错误。

示例代码:下面是一个render函数中的部分代码:

const types = ['all','ongoing']
{types.map((type, index) => {
  const { data } = this.props[type]; // 外层map定义一个临时变量
  return (
    current == index && (
      <ActivityContainer>
         {data && data.length ? ( // 这里有一个条件判断,引用了外层map变量
            data.map(item => {
              return (
                <View style={{ // 内层map也有一个临时变量
                          width: fontSizeBase,
                          height: fontSizeBase,
                          lineHeight: fontSizeBase
                }}>
                          // ...后面省略
                          // ...后面省略
                          // ...后面省略

内层map用到一个临时变量:

{
  width: fontSizeBase,
  height: fontSizeBase,
  lineHeight: fontSizeBase
}

查看该部分View的编译结果:

<view style="{{item.$loopState__temp7}}" />

编译后的js:

var loopArray0 = types.map(function(type, index) {
            type = {
              $original: (0, _index.internal_get_original)(type)
            };

            var data = _this4.__props[type.$original].data; // 外层map的临时变量,正常
   // ...
            // 内层map的临时变量
            var $loopState__temp7 =
                      current == index
                        ? type.data && type.data.length // 这里的type中实际上并不包含data属性
                          ? {
                              width: fontSizeBase,
                              height: fontSizeBase,
                              lineHeight: fontSizeBase
                            }
                          : null
                        : null;

如上,我期望$loopState__temp7是style对象,但是最终结果是null。原因是三元表达式中的第二个条件编译错误。

如果我在render函数中先将style保存为一个变量,就不会出现这个问题:

render() {
    const { current } = this.state;
    const types = [TYPE_ALL, TYPE_ONGOING];

    const fontSizeBase = Taro.pxTransform(28);

    const style = {
      width: fontSizeBase,
      height: fontSizeBase,
      lineHeight: fontSizeBase
    };

// ... 省略
// map函数中:
                <View style={style} />

我的想法

似乎在map中不在本map函数作用域中的变量的时候,会默认它是map的回调函数的第一个参数的属性?感谢您解答。

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions