iT邦幫忙

0

更改資料庫內容使FlatList 更新

我有一個SQLite資料庫

id|title|content|date|
------------------------
1 |標題 |  內容  |y/m/d| 
------------------------

這是從資料庫拿到的資料格式

const{items}=this.state
console.log(items)
<FlastList  data={items}>

Array [
  Object {
    "content": "",
    "date": "",
    "id": ,
    "title": "1sss",
  },
  Object {
    "content": "",
    "date": "",
    "id": ,
    "title": "",
  },

新增、移除 然後更新state都可以成功更新flatlist,但是更改拿到的內容比如"content": 新增內容似乎並不會讓flastList更新,有嘗試過
extradata={this.state}然後設定一個會改變狀態的state,也沒起作用,這種功能非常常見但我找不到解決辦法,有可能是我思路錯了,想問問是甚麼原因造成的。

更新:
應該說操作資料庫去更新裡面的鍵值,我有一個文字編輯器可以編輯文章然後更改內容

if(params.type==1){
      db.transaction((tx) => {
        tx.executeSql(
          "update diary set(content,title,date)=(?,?,?) where id= ?",
          [this.state.content, this.state.title, this.state.date.getFullYear(),params.cardId],
          ToastAndroid.show("更新成功!", ToastAndroid.SHORT)
        );

會從Textinput拿資料更新,然後我有一個HomeScreen會從資料庫拿資料顯示在flatlist中,問題就出在編輯完HomeScreen重新render之後,flatlist的內容還是沒有變。


更新:
嘔我使用了一個笨方法解決,我複製items叫做items2

const item2 ={this.state.item}

然後在handleRefresh中替換原本的item

handleRefresh(){
    this.setState({items: item2})
}

然後下拉就能更新了,不過理想還是希望他能自己更新,目前想法是使用timer定時更新可是感覺資料量大的時候一定會爆炸

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
iT邦新手 2 級 ‧ 2020-04-07 09:38:29

可以試試看 useEffect()。
你使用 class 寫法,可以試試用 componentDidMount / componentDidUpdate

我是使用class,但是react並不會知道資料庫內容有更改所以不會改變state,準備嘗試navigation回來帶一個isEdit:true 然後重新覆蓋state,現在遇到更大的問題了
ios跟sql在Textinput資料交互的時候編碼不對

iT邦新手 2 級 ‧ 2020-04-14 16:23:46 檢舉

可以試試 flatlist 的 refreshing,有新資料來時讓他變成 true

我要發表回答

立即登入回答