Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

使用map嵌套时,用this.state得到TypeError: Cannot read property 'file' of undefined #886

Closed
nyrf opened this issue Oct 19, 2018 · 5 comments
Assignees

Comments

@nyrf
Copy link

nyrf commented Oct 19, 2018

  state = {
    selectedSkus: {},
    skuKeys: {},
    skuSpecs: {},
    skuDefault: []
  }
const keys = this.state.skuKeys
    return (
      <View>
        {
          Object.keys(keys).map(function (key) {
            return(
              <View className='item' key={key}>
              <View className="title">{key}</View>
              <View className='skus'>
              {
                Object.keys(keys[key]).map(function (k) {
                  return(
                    <View key={k} className={`sku ${keys[key][k].active ? 'active' : '' }`} onClick={this.onSkuClick.bind(this, keys[key][k], k, keys[key], key)}>
                      {k}
                      {this.state.skuKeys[key][k].active}
                    </View>
                  )
                })
              }
              </View>
            </View>
            )
          })
        }
      </View>
    )
错误  组件编译  组件src/components/sku/sku.js编译失败!
TypeError: Cannot read property 'file' of undefined

其中this.state.skuKeys的数据是从上级props中传过来的,
如果 把 {this.state.skuKeys[key][k]} 这一句换成 keys[key][k].active 就不会报错,不过onClick中setState更新了skuKeys,比如把其中一项的active设置为true, 调试也显示skuKeys是更新了的,但这里map得到的内容,keys[key][k].active还是显示false

@yuche
Copy link
Contributor

yuche commented Oct 19, 2018

方便麻烦贴一下你的数据源吗

@nyrf
Copy link
Author

nyrf commented Oct 19, 2018

从props传过来的keys是这样的

{
  '颜色': {
   '红': {active: false, disabled: false, name: '红'},
   '黄': {active: false, disabled: false, name: '黄'}
  },
  '大小': {
    'M': {active: false, disabled: false, name: 'M'},
    'L': {active: false, disabled: false, name: 'L'}
  }
}

这里我把props得到的keys给了state的skuKeys. 然后更新的都是skuKeys

@nyrf
Copy link
Author

nyrf commented Oct 19, 2018

skuKeys 更新问题解决了,这里const keys = this.state.skuKeys, 这个地方,不可以用和props中keys一样的名称,换成其它名称就好了,

不过{this.state.skuKeys[key][k]} 这句还是报错,现在直接先 const { skuKeys } = this.state,然后再 {skuKeys[key][k].active},这样就可以了

@yuche
Copy link
Contributor

yuche commented Oct 23, 2018

请问你现在用的版本是哪个

@nyrf
Copy link
Author

nyrf commented Oct 23, 2018

@yuche 最新版
👽 Taro v1.1.0-beta.10

1.1.0-beta.10

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants