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

componentDidShow h5下 this undefined #3333

Closed
zhangzhenfei opened this issue Jun 5, 2019 · 6 comments
Closed

componentDidShow h5下 this undefined #3333

zhangzhenfei opened this issue Jun 5, 2019 · 6 comments
Assignees

Comments

@zhangzhenfei
Copy link

zhangzhenfei commented Jun 5, 2019

问题描述
[问题描述:站在其它人的角度尽可能清晰地、简洁地把问题描述清楚]
h5下 componentDidShow 生命周期中,this获取不到,无法调用组件方法

复现步骤
[复现问题的步骤]

[或者可以直接贴源代码,能贴文字就不要截图]
image

componentDidShow  h5下 this作用域获取不到,导致方法无法调用

// 这里可以贴代码

// ```js
// 代码放这里(前后的 "```" 有助 Mardown 整理代码格式和加入代码高亮)
// ```

// 提供完整可复现的代码和整理好代码格式,有助于我们快速定位问题,节省你我时间。
// 代码提供不全或代码格式混乱的 issues 【有可能被忽略】,烦请各位注意。

期望行为
[这里请用简洁清晰的语言描述你期望的行为]

报错信息

[这里请贴上你的完整报错截图或文字]

系统信息

Taro v1.2 及以上版本已添加 taro info 命令,方便大家查看系统及依赖信息,运行该命令后将结果贴下面即可。

  • 操作系统: [e.g. Windows 10]
  • Taro 版本 1.3.0 -beta6
  • Node.js 版本 [e.g. v9.0.0]
  • 报错平台 [h5, weapp]

补充信息
[可选]
[根据你的调查研究,出现这个问题的原因可能在哪里?]

@taro-bot
Copy link

taro-bot bot commented Jun 5, 2019

欢迎提交 Issue~

如果你提交的是 bug 报告,请务必遵循 Issue 模板的规范,尽量用简洁的语言描述你的问题,最好能提供一个稳定简单的复现。🙏🙏🙏

如果你的信息提供过于模糊或不足,或者已经其他 issue 已经存在相关内容,你的 issue 有可能会被关闭。

Good luck and happy coding~

@yuche yuche added the H5 label Jun 5, 2019
@taro-bot taro-bot bot assigned Littly Jun 5, 2019
@taro-bot
Copy link

taro-bot bot commented Jun 5, 2019

CC @Littly

@zhangzhenfei
Copy link
Author

补充一下,页面使用了mobx注解会出现此问题,去掉就好了

@Inject('indexStore')
@observer

image

去掉后

image

@luckyadam
Copy link
Member

贴一下完整的代码

@zhangzhenfei
Copy link
Author

import { ComponentType } from 'react'
import Taro, { Component, Config } from '@tarojs/taro'
import { View, ScrollView } from '@tarojs/components'
import { AtButton, AtNavBar } from 'taro-ui'
import { observer, inject } from '@tarojs/mobx'

import { findPageList } from './assets/api'
import { IResourceType } from './assets/interface'
import { IListResult } from '@/interfaces/index'
import { log, navigateTo, navigateBack } from '@/utils/common'

const styles = require('./index.module.scss')

type PageStateProps = {
  indexStore: {
    editResourceType: any
    setEditResourceType: Function
  }
}

interface Index {
  props: PageStateProps
}

interface IState {
  isEdit: boolean
  pageNo: number
  hasPre: boolean
  result: IResourceType[]
}

@inject('indexStore')
@observer
class Index extends Component {
  config: Config = {
    navigationBarTitleText: '物资种类管理'
  }

  public state: IState = {
    isEdit: false,
    pageNo: 1,
    hasPre: true,
    result: []
  }

  constructor(props) {
    super(...arguments)
  }

  componentWillMount() {
    log('加载数据')
    this.loadData()
  }

  componentWillReact() {
    log('componentWillReact', this)
  }

  componentDidMount() {
    log('componentDidMount', this)
  }

  componentWillUnmount() {
    log('componentWillUnmount', this)
  }

  componentDidShow() {
    console.log('componentDidShow', this)
  }

  componentDidHide() {
    log('componentDidHide', this)
  }

  navigateBack = () => {
    navigateBack()
  }

  async loadData() {
    const responseRes = await findPageList(this.state.pageNo)
    if (responseRes.head.ret === 0) {
      const data: IListResult<IResourceType> = responseRes.data
      const { result, prePage, hasPre } = data
      this.setState({ result, pageNo: prePage, hasPre })
    }
  }

  handleToggleStatus() {
    this.setState({ isEdit: !this.state.isEdit })
  }

  handleNewOrEdit(item) {
    this.props.indexStore.setEditResourceType(item || {})
    this.setState({ isEdit: false })
    navigateTo('/pages/index/pages/types-edit/index', { isEdit: item ? 1 : 0 })
  }

  render() {
    const { isEdit, result } = this.state
    return (
      <View className={[styles.container, 'container'].join(' ')}>
        <View className={styles.nav}>
          <AtNavBar
            color="#000"
            title="物资种类管理"
            leftIconType="chevron-left"
            onClickLeftIcon={this.navigateBack.bind(this)}
          />
          <View
            className={[styles.tool, isEdit ? styles.finish : ''].join(' ')}
            onClick={this.handleToggleStatus.bind(this)}
          >
            {isEdit ? '完成' : '管理'}
          </View>
        </View>
        <View className={styles.wrap}>
          {!result || result.length === 0 ? (
            <View className={styles.emptyText}>暂无添加物资类型</View>
          ) : (
            <ScrollView className={[styles.container, 'scroll-container'].join(' ')} scrollY={true}>
              {result.map((item, index) => {
                return (
                  <View className={styles.listItem} key={index}>
                    <View className={styles.itemContent}>
                      <View className={styles.title}>{item.name}</View>
                      <View className={styles.remark}>{item.remark}</View>
                    </View>
                    {isEdit && (
                      <View className={styles.itemTool}>
                        <View className={styles.btnWrap}>
                          <AtButton type="primary" size="small" onClick={this.handleNewOrEdit.bind(this, item)}>
                            编辑
                          </AtButton>
                        </View>
                        <View className={styles.btnWrap}>
                          <AtButton type="secondary" size="small">
                            删除
                          </AtButton>
                        </View>
                      </View>
                    )}
                  </View>
                )
              })}
            </ScrollView>
          )}
          {!isEdit && (
            <AtButton type="primary" className={styles.btn} onClick={this.handleNewOrEdit.bind(this, false)}>
              新增物资种类
            </AtButton>
          )}
        </View>
      </View>
    )
  }
}

export default Index as ComponentType

@luckyadam luckyadam added the mobx label Jun 10, 2019
@zhangzhenfei
Copy link
Author

问题比较严重,取不到this的话,意味着回退页面监听失效,页面无法刷新,可以帮忙这个版本修复吗,项目马上要测试了~~~ @luckyadam

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

4 participants