2016-12-25 18 views
0
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

setState是異步的。它的第二個參數是一個回調函數,當狀態被實際更新時,您可以使用它來做出反應。

+0

確定,將狀態更新觸發頁面的重新渲染(我不需要在這個函數中做任何其他的事情,我只需要頁面另一部分的狀態) – Himmators

+0

是的,setstate在處理後會導致重新渲染。 – Tannin

0

setState不立即更新狀態。它會創建一個待處理的轉換。

如果你只想的setState後檢查組件的狀態,像這樣做:

this.setState({fullScreen: true},() => { 
    // I am triggered after the state is set 
    console.log(this.state) 
}) 

讀到它在here

相關問題