2017-02-15 33 views
0

上的狀態變化我有以下代碼:Reactjs - componentWillMount的setState導致卸載的組件

componentWillMount() { 
    this.props.actions.A().then(result => { 
     this.setState({ a: result }); 
    }); 
} 

現在正在發生的事情是,如果我切換頁面快,我收到警告說:setState(...): Can only update a mounted or mounting...

我能做些什麼來防止這種情況發生? (顯然使用IsMounted屬性可以解決它,但是作爲一個讀取其過期)

回答

0

嘗試使用componentDidMount生命週期掛鉤。因此,這將是

componentDidMount() { 
    this.props.actions.A().then(result => { 
     this.setState({ a: result }); 
    }); 
} 

以下是FB說。 「componentDidMount()是一個組件安裝後立即調用初始化需要DOM節點應該在這裏如果你需要從遠程端點加載數據,這是一個實例化網絡請求的好地方,在此方法中設置狀態將觸發重新渲染。「

+0

不好!這些文件說使用componentWillMount – omriman12

+0

你可以給我鏈接到你讀的地方嗎? 'componentDidMount'用於設置組件的初始狀態以及從API獲取數據。 'componentWillMount'會在'componentDidMount'之前觸發,並且您正嘗試在尚未安裝的組件中設置狀態。這就是爲什麼你會得到這個錯誤信息。 –

+0

這裏是另一個線程討論爲什麼它不是一個反模式來調用'componentDidMount'中的'setState'。 –