反应本机搜索栏-错误:未定义不是一个函数(在'... this.state.books.filter ...'附近)

时间:2019-11-14 13:50:20

标签: javascript firebase react-native firebase-realtime-database searchbar

我无法弄清楚我在做什么错。

我添加了一个搜索栏,但是当我在文本字段中写一些内容时,它给了我错误:“未定义不是函数(在'... this.state.books.filter ...'附近)“

下面是我的一些代码。

我在做什么错了?

 state = {
    books: {},
};
componentDidMount() {
        firebase
        .database()
        .ref('/Books')
        .on('value', snapshot => {
            this.setState({ books: snapshot.val() });
        });
}
searchBooks = value => {
    const { books } = this.state;
    const bookArray = Object.values(books);
    const filteredBooks = bookArray.filter(book => {
        let bookLowercase = (book.bookname).toLowerCase();
        let searchTermLowercase = value.toLowerCase();
        return bookLowercase.indexOf(searchTermLowercase) > -1;
    });
    this.setState({ books: filteredBooks });
};

render() {
    const { books } = this.state;
    if (!books) {
        return null;
    }
    const bookArray = Object.values(books);
    const bookKeys = Object.keys(books);
    return (

        <View style={styles.container}>
            {/*Searchbar */}
            <View style={{ height: 80, backgroundColor: '#c45653', justifyContent: "center", paddingHorizontal: 5 }}>
                <View style={{ height: 50, backgroundColor: 'white', flexDirection: 'row', padding: 5, alignItems: 'center' }}>
                    <TextInput
                        style={{
                            fontSize: 24,
                            marginLeft: 15
                        }}
                        placeholder="Search"
                        onChangeText={value => this.searchBooks(value)}
                    />
                </View>
            </View>

            <FlatList
                style={{ backgroundColor: this.state.searchBarFocused ? 'rgba(0,0,0,0.3)' : 'white' }}
                data={bookArray}
                keyExtractor={(item, index) => bookKeys[index]}
                renderItem={({ item, index }) => (
                    <BookListItem
                        book={item}
                        id={bookKeys[index]}
                        onSelect={this.handleSelectBook}
                    />
                )}
            />
        </View>
    );

1 个答案:

答案 0 :(得分:2)

您正在将this.state.books初始化为Object

state = {
    books: {},
};

对象没有过滤功能。您可能想改用Array

state = {
    books: [],
};

然后,您将可以将this.state.books.filter()与数组的filter函数一起使用。