【发布时间】: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