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

在子组件中的componentDidMount调用setState更新数据,在它的回调里面获取数据却没有立即更新 #1185

Closed
cd-dongzi opened this issue Nov 20, 2018 · 3 comments
Assignees

Comments

@cd-dongzi
Copy link

问题描述
在子组件中的componentDidMount调用setState更新数据,在它的回调里面获取数据却没有立即更新

复现步骤

// 父组件, page页面, 在回调里面获取数据是能获取到更新后的值(b = 2),正常
import Taro, { Component } from '@tarojs/taro'
import { View } from '@tarojs/components'
import Child from './child'

type props = {}
type state = {
  b: number
}

export default class Test extends Component<props, state> {
  constructor(props) {
    super(props)
    this.state = {
      b: 1
    }
  }
  componentDidMount() {
    this.setState({
      b: 2
    }, () => {
      console.log('b => ' + this.state.b) // b => 2
    })
  }
  render () {
    return (
      <View className="test">
        <Child></Child>
      </View>
    )
  }
}
// 子组件, page页面, 在回调里面获取数据却还是1,得过会才会变成2,这是为啥
import Taro, { Component } from '@tarojs/taro'
import { View } from '@tarojs/components'

type props = {}
type state = {
  a: number
}

export default class Child extends Component<props, state> {
  constructor(props) {
    super(props)
    this.state = {
      a: 1
    }
  }
  componentDidMount() {
    this.setState({
      a: 2
    }, () => {
      console.log('a => ' + this.state.a) // a => 1
      setTimeout(() => {
        console.log('a1 => ' + this.state.a) // a1 => 2
      }, 0)
    })
  }
  render () {
    return (
      <View className="child">
        Child
      </View>
    )
  }
}

期望行为
希望在子组件的setState的回调里面也能直接获取到最新数据

报错信息
w5alwqe3ok5ok6 lshi 73q

系统信息

  • 操作系统: [e.g. Windows 10]
  • Taro 版本 [e.g. v.1.1.0]
  • Node.js 版本 [e.g. v8.12.0]
  • 报错平台 [weapp]
@taro-bot
Copy link

taro-bot bot commented Nov 20, 2018

欢迎提交 Issue~

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

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

Good luck and happy coding~

@luckyadam
Copy link
Member

升级到最新版本试试

@cd-dongzi
Copy link
Author

我升级到了 1.1.9 这个版本试了, 也还是一样

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

3 participants