【问题标题】:React Native Redux: this.setState is not changing stateReact Native Redux:this.setState 没有改变状态
【发布时间】:2018-06-08 15:11:11
【问题描述】:

this.setState({device}) 根本不更新状态,除非我用“this.state.device = __”强制它,但它仍然是一个问题,因为组件不会重新渲染。我尝试使用回调函数,例如:

this.setState({device: selectedDeviceId}, () => {
    console.log(this.state.device)
})    

但代码根本没有记录,这表明 setState 甚至没有被调用。

class Stats extends React.Component {
  state = {
    viewType: 'day',
    dt: moment(),
    device: {}
  }
  getDevice = () => {
    const devices = this.props.devices || []
    const selectedDeviceId = this.props.selectedDeviceId

    devices.forEach((d) => {
      if (d._id === selectedDeviceId) this.setState({device: d})
    })
    if (!this.state.device._id && devices.length) {
      this.setState({device: devices[0]})
    }
    this.getUsage()
  }

  componentWillMount () {
      console.log('Enter StatsScreen.componentWillMount')
      let dt = this.state.dt
      const date = moment(dt).format('YYYY-MM-D')
      console.log(date)
      this.getDevice()
  }
}

【问题讨论】:

  • 你能分享一下console.log吗?以及 "!this.state.device._id && devices.length" 的值,以确保 if 语句的计算结果为 true。
  • 如果你也可以插入你的渲染函数,它会提供更多的想法
  • 为什么你的“componentDidMount”在你的 Stats 类之外?
  • 抱歉问题中的拼写错误。 ComponentWillMount 在 Stats 类中
  • console.log(d) = Object __immutable_invariants_hold:true _id:"5a1654b2fc92299a7f00001c" alert_disabled:false alert_duration:1 alert_interval:60 alert_volume:1...等

标签: react-native redux native setstate


【解决方案1】:

问题是您没有使用 React Native 状态,而是使用了一个名为 state 的变量。通过编写构造函数生命周期方法并将 this.state = 放在那里进行初始化来解决此问题。

顺便说一句,避免在 willMount 生命周期方法中执行此类操作,然后在 didMount 中执行此操作,这样您就不会阻塞 UI。

【讨论】:

  • 我在没有任何运气的情况下尝试了构造函数 (props) { super(props) this.state = { viewType: 'day', dt: moment(), device: {} } }
  • 在 didMount 中设置状态修复了这个问题。谢谢!
猜你喜欢
  • 2018-05-06
  • 2020-05-03
  • 2019-03-22
  • 2019-09-23
  • 1970-01-01
  • 2015-12-21
  • 1970-01-01
  • 2022-07-06
  • 2018-01-09
相关资源
最近更新 更多