class ProductCarousel extends Component {
constructor (props) {
super(props)
this.state = {
active: -1,
fullScreen: false
}
this.flky = {}
}
componentDidMount (props) {
this.flky = new Flickity('.carousel', flickityOptions)
this.flky.on('select', () => {
this.setState({ active: this.flky.selectedIndex })
})
}
fullScreen () {
this.setState({ fullScreen: true })
console.log(this.state)
}
render () {
const images = this.props.images
return (
<div>
<div className='carousel'>
{images.map((url, i) => (
<img
className='productPhoto'
key={i.toString()}
onClick={this.fullScreen.bind(this)}
src={stripUrl(url)}
style={{maxWidth: '100%'}}
/>
))}
</div>
</div>
)
}
}
我在js中有这个组件,在函数fullScreen中,我希望this.state.fullScree
n为真,但它仍然是假的,为什么?
答案 0 :(得分:0)
setState是异步的。它的第二个参数是一个回调函数,您可以用它来响应状态实际更新的时间。
答案 1 :(得分:0)
setState不会立即更新状态。它会创建一个挂起的转换。
如果要在setState之后检查组件的状态,请执行以下操作:
this.setState({fullScreen: true}, () => {
// I am triggered after the state is set
console.log(this.state)
})
通过here
了解相关信息