从FlatList中删除项目后,UI无法正确更新

时间:2018-07-21 17:50:46

标签: reactjs react-native react-native-flatlist

我正在创建一个应用,希望将书添加到书架中。现在,该应用程序包含两个选项卡,BookShelf显示了所有已添加书籍的平面列表,AddBook现在包含了两个按钮,用于添加一些虚拟数据以测试功能。

这些书作为对象存储在AsyncStorage中的数组中,我通过获取存储在AsyncStorage中的数据来更新BookShelf组件的状态。将书籍添加到单位列表可以很好地工作,但是当从列表中删除某项时,单位列表的UI不能正确更新,我遇到一些问题。现在,我必须切换到“ AddBook”选项卡并返回到BookShelf,以触发重新渲染已删除所选项目的单位列表。有什么想法可以解决这个问题,并在我按下删除按钮时直接重新呈现单位列表吗?

这些是我用于在AsyncStorage中添加,获取和删除数据的功能:

    export function addData(book) {

    AsyncStorage.getItem('@books')
    .then((books) => {
    let b = books ? JSON.parse(books) : [];
    b.push(book);
    AsyncStorage.setItem('@books', JSON.stringify(b));
  });  
}

export function getData() {

    let books = AsyncStorage.getItem('@books')
    .then(books => (JSON.parse(books)))

    return books;
}

export function removeData(id) {

    AsyncStorage.getItem('@books')
    .then((books) => {
    let allBooks = JSON.parse(books)

    let filteredBooks = allBooks.filter(item => item.id != id);

      AsyncStorage.setItem('@books', JSON.stringify(filteredBooks));
   }) 
}

当在平面列表中的某个项目上按Delete键时,这是我在BookShelf组件中的功能:

    updateBookShelf = (id) => {
    removeData(id), () => {  
        getData().then((data) => {
            this.setState({
                books: data
            })
        })}

以下是一个GIF,用于说明当我尝试删除项目时应用程序的行为:

enter image description here

1 个答案:

答案 0 :(得分:0)

尝试像下面那样返回承诺:

@IBOutlet var buttons: [UIButton]!
var lastTappedButton: UIButton?

@IBAction func button_Tap(_ sender: UIButton) {

    for button in buttons {
        if let lastTappedButton = lastTappedButton, lastTappedButton != sender {
            button.backgroundColor = .white
        }
        if button.tag == sender.tag { 
            button.backgroundColor = .blue 
            lastTappedButton = button
        }
    }
}

export function getData() { return AsyncStorage.getItem('@books') .then(books => books.json()) } 是一个异步函数,而.json()根据this stackoverflow question是同步的。