React Native Redux:this.setState 没有改变状态
React Native Redux: this.setState is not changing state
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()
}
}
问题是您没有使用 React Native state,您使用的是您创建的名为 state 的变量。通过编写构造函数生命周期方法并将 this.state = 放入其中进行初始化来解决此问题。
顺便说一句,避免在 willMount 生命周期方法中做这样的事情,在 didMount 中做这样你就不会阻塞 UI。
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()
}
}
问题是您没有使用 React Native state,您使用的是您创建的名为 state 的变量。通过编写构造函数生命周期方法并将 this.state = 放入其中进行初始化来解决此问题。
顺便说一句,避免在 willMount 生命周期方法中做这样的事情,在 didMount 中做这样你就不会阻塞 UI。