javascript - 為什么這種情況state改變不刷新頁(yè)面?
問題描述
先說背景:頁(yè)面上是一個(gè)巨大的flatlist,里面有3個(gè)item,我在第三個(gè)item內(nèi)部的最下面也就是整個(gè)外層flatlist的最下面有一個(gè)flatlist,這個(gè)flatlist加載的是state中的數(shù)據(jù),需要做上拉加載功能,因?yàn)閮?nèi)部的flatlist拿不到下拉事件,所以我在最外層寫了上拉加載的方法,獲取到數(shù)據(jù)放到state中,這樣就改變了里面的數(shù)據(jù)。但是,雖然state變了,頁(yè)面卻沒刷新。后臺(tái)打印確定state改變了
上個(gè)簡(jiǎn)要的代碼
constructor(props) {super(props)this.state = { data: [{'key': 1}, {'key': 2}, {'key': 3}],}this._changeData = this._changeData.bind(this); } _changeData(){this.setState({ data :[{'key': 1}, {'key': 2}, {'key': 3},{'key': 4},{'key': 5}],}) } _renderItem = ({item}) => {switch (item.key) { case 1:return ( <View><Text style={{height: 200}}>1111</Text> </View>); case 2:return ( <View><Text style={{height: 200}}>ke2222y2</Text> </View>); case 3:return ( //這個(gè)flatlist需要做上拉加載 <FlatListdata={this.state.data} renderItem={({item}) => <View style={{height: 200}}><Text>{item.key}</Text></View>} />)} } render() {const {navigate} = this.props.navigation;let user = {’name’: ’zy’, age: 18}return ( <View><Text onPress={() => navigate(’Two’, {user: user})}>Home</Text><FlatList data={[{'key': 1}, {'key': 2}, {'key': 3}]} renderItem={this._renderItem} onEndReached={this._changeData} onEndReachedThreshold={0.3}/><Text onPress={() => navigate(’Two’, {user: user})}>Home</Text> </View>) }
我寫的這個(gè)demo是可以實(shí)現(xiàn)的但是白天在項(xiàng)目里,那個(gè)數(shù)據(jù)是從網(wǎng)絡(luò)獲取過來的一個(gè)數(shù)組我用一個(gè)新的數(shù)組a把state里的數(shù)組放進(jìn)去,再把拿過來的數(shù)組也放進(jìn)去,最后把這個(gè)數(shù)組a賦值給state但發(fā)現(xiàn)并沒有變化,頁(yè)面沒有刷新
問題解答
回答1:順便問一下有什么更好的方法
回答2:你只能通過setState去觸發(fā)render。
this.setState({ data: anotherData})
不能通過直接賦值去觸發(fā)
this.state.data = anotherData
雖然不知道你真正實(shí)現(xiàn)是怎樣的,但我估計(jì)你用了后者這種方式。
相關(guān)文章:
1. index.php錯(cuò)誤,求指點(diǎn)2. css - 手機(jī)qq打開網(wǎng)頁(yè)無(wú)法使用文件上傳功能?3. html5 - css3 scale 從0到1在有的手機(jī)上,圖像會(huì)變模糊4. css3 - 微信下拉漏出文件來源怎么禁止 頁(yè)面中仍有需要滾動(dòng)的地方5. 一個(gè)PHP文件在中英不同狀態(tài)怎么運(yùn)行對(duì)應(yīng)的JS文件6. python小白,問一個(gè)關(guān)于可變類型和不可變類型底層的問題7. html5 - 頁(yè)面在手機(jī)屏幕觸摸下拉會(huì)刷新是怎么回事8. 瀏覽器空白html文檔報(bào)未定義join錯(cuò)9. javascript - vue 2.0 @click.self 不觸發(fā)10. angular.js - Angular開發(fā)的單頁(yè)面應(yīng)用,如何正確地實(shí)現(xiàn)在微信里的網(wǎng)頁(yè)授權(quán)和調(diào)用js sdk
