javascript - 為什么這種情況state改變不刷新頁面?
問題描述
先說背景:頁面上是一個巨大的flatlist,里面有3個item,我在第三個item內部的最下面也就是整個外層flatlist的最下面有一個flatlist,這個flatlist加載的是state中的數據,需要做上拉加載功能,因為內部的flatlist拿不到下拉事件,所以我在最外層寫了上拉加載的方法,獲取到數據放到state中,這樣就改變了里面的數據。但是,雖然state變了,頁面卻沒刷新。后臺打印確定state改變了
上個簡要的代碼
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 ( //這個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>) }
我寫的這個demo是可以實現的但是白天在項目里,那個數據是從網絡獲取過來的一個數組我用一個新的數組a把state里的數組放進去,再把拿過來的數組也放進去,最后把這個數組a賦值給state但發現并沒有變化,頁面沒有刷新
問題解答
回答1:順便問一下有什么更好的方法
回答2:你只能通過setState去觸發render。
this.setState({ data: anotherData})
不能通過直接賦值去觸發
this.state.data = anotherData
雖然不知道你真正實現是怎樣的,但我估計你用了后者這種方式。
相關文章:
1. javascript - 深夜被問題困擾求解惑,rn的API之PermissionsAndroidd的問題2. mysql - 我的myeclipse一直連顯示數據庫連接失敗,不知道為什么3. javascript - 最近用echarts做統計圖時遇到兩個問題!!4. docker綁定了nginx端口 外部訪問不到5. 前端 - html5 audio不能播放6. docker images顯示的鏡像過多,狗眼被亮瞎了,怎么辦?7. git - webstorm窗口中左側列表的文件名顏色怎么修改8. html - radio的使用時如何避免整個頁面只能選一個的情況9. mysqld無法關閉10. java - Activity 進入后臺再次傳值?

網公網安備