фильтр поиска не может отфильтровать мои фиктивные данные - PullRequest
0 голосов
/ 14 апреля 2020

Я не могу отфильтровать ложные данные. Я не знаю, что я делаю неправильно. и нет ошибки. Всякий раз, когда я печатаю внутри панели поиска, вывод ничего не фильтрует. Я могу отображать содержимое mockData, но не могу фильтровать эти mockData.

class BookshelfChanger extends Component {
      state = {
        value: this.props.shelf
      };
      handleChange = event => {
        this.setState({ value: event.target.value });
        this.props.onMove(this.props.book, event.target.value);
      };
      render() {
        return (
          <div className="book-shelf-changer">
            <select value={this.state.value} onChange={this.handleChange}>
              <option value="move" disabled>
                Move to...
              </option>
              <option value="currentlyReading">Currently Reading</option>
              <option value="wantToRead">Want to Read</option>
              <option value="read">Read</option>
              <option value="none">None</option>
            </select>
          </div>
        );
      }
    }
    class SearchBooks extends Component {
      render() {
        const { books,  onResetSearch, onSearch} = this.props;
        console.log(books);
        return (
          <div className="search-books">
            <SearchBar onSearch={onSearch} onResetSearch={onResetSearch} />
            <SearchResults
              books={books}
              />
          </div>
        );
      }
    }
    const SearchBar = props => {
      const {onSearch, onResetSearch } = props;
      return (
        <div className="search-books-bar">
          <CloseSearchButton onResetSearch={onResetSearch} />
          <SearchBooksInput onSearch={onSearch} />
        </div>
      );
    };

    const CloseSearchButton = props => {
      const { onResetSearch } = props;
      return (
        <Link to="/">
          <button className="close-search" onClick={onResetSearch}>
            Close
          </button>
        </Link>
      );
    };

    class SearchBooksInput extends Component {
      state = {
        value: '',
        data:getAll
      };
      handleChange = event => {
        const val = event.target.value;
        this.setState({ value: val });
        console.log(this.state.data)
      };
      render() {
        const { value, data } = this.state;
        // const lowercasedFilter = value.toLowerCase();
        const filteredData = data.filter(book => {
          return Object.keys(book)
        });
        console.log(filteredData)
        return (
          <div className="search-books-input-wrapper">
            <input
              type="text"
              value={value}
              placeholder="Search by title or author"
              onChange={this.handleChange}

            />
             {filteredData.map(book => (
              <Book
              key={book.id}
              book={book}
              shelf= 'none'

            />
            ))}

          </div>
        );
      }
    }
    const SearchResults = props => {
      const { books} = props;
      // const booksOnThisShelf = books.filter(book => book.shelf === shelf);
      return (
        <div className="search-books-results">
          <ol className="books-grid">
            {books.map(book => (

              <Book
                key={book.id}
                book={book}
                shelf= 'none'

              />
            ))}
          </ol>
        </div>
      );
    };

Книга:

const Book = props => {
      const { book, shelf, onMove } = props;
      return (
        <li>
          <div className="book">
            <div className="book-top">
              <div
                className="book-cover"
                style={{
                  width: 128,
                  height: 193,
                  backgroundImage: `url(${book.imageLinks.thumbnail})`
                }}
              />
              <BookshelfChanger book={book} shelf={shelf} onMove={onMove} />
            </div>
            <div className="book-title">{book.title}</div>
            <div className="book-authors">{book.authors}</div>
          </div>
        </li>
      );
    };

getAll (mockData):

    const getAll = [     
    {
          title: "the book of RA",
          authors: ['Robert Galbraith'],
          imageLinks: {
            thumbnail:
            'https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcQK_a32ZoQ0mUQ8hHj0rS-ZXSoiA9ujpS1thED04xWG-l-G8bTB&usqp=CAU'  
          },
          id: 'evuwdDLfAyYw',
          shelf: 'wantToRead',
        },
        {
          title: 'bahamut dragon god',
          authors: ['Liaquat Ahamed'],
          imageLinks: {
            thumbnail:
              'https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcSPNgP0LX5_1psjQracNJGJ_qhuFcK_uyf9cumzjEV_9qOsBBi0&usqp=CAU'
          },
          id: '74XNzF_al3Mr',
          shelf: 'wantToRead',
        },  
        {
          title: 'Needful Things',
          authors: ['Stephen King'],
          imageLinks: {
            thumbnail:
              'http://books.google.com/books/content?id=jAUODAAAQBAJ&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api',
          },
          ]

профиль gitHub

Выходное изображение показано здесь. ошибки нет, поэтому я не могу понять, в чем проблема

1 Ответ

0 голосов
/ 14 апреля 2020

Я пытался решить вашу проблему. надеюсь, это поможет вам. Пожалуйста, проверьте приведенный ниже пример

Книжная полка. js

import React, {useState} from 'react';
import {Component} from "react";
import Link from "@material-ui/core/Link";
import Book from "./Book";

class BookshelfChanger extends Component {
    state = {
        value: this.props.shelf
    };
    handleChange = event => {
        let filteredBooks =  getAll.filter(book => book.shelf === event.target.value);
        this.setState({isFiltered: true, filteredBooks: filteredBooks});
    };

    render() {
        return (
            <div className="book-shelf-changer">
                <select value={this.state.value} onChange={this.handleChange}>
                    <option value="move" disabled>
                        Move to...
                    </option>
                    <option value="">Please Select</option>
                    <option value="currentlyReading">Currently Reading</option>
                    <option value="wantToRead">Want to Read</option>
                    <option value="read">Read</option>
                    <option value="none">None</option>
                </select>
                <SearchBooks />
                {
                    this.state.isFiltered? <SearchResults books={this.state.filteredBooks}/> : null
                }
            </div>
        );
    }
}

class SearchBooks extends Component {

    constructor(props) {
        super(props);
        this.state = {
            resultFound: false
        }
    }

    resetSearch = e => {
        this.setState({resultFound: false, searchBooks: null});
    };

    search = books => {
        this.setState({resultFound: true});
        this.setState({searchBooks: books});
    };

    render() {
        return (
            <div className="search-books">
                <SearchBar onSearch={this.search} onResetSearch={this.resetSearch}/>
                {
                    this.state.resultFound ? <SearchResults books={this.state.searchBooks}/> : null
                }
            </div>
        );
    }
}

const SearchBar = props => {
    const {onSearch, onResetSearch} = props;
    return (
        <div className="search-books-bar">
            <SearchBooksInput onSearch={onSearch}/>
            <CloseSearchButton onResetSearch={onResetSearch}/>
        </div>
    );
};

const CloseSearchButton = props => {
    const {onResetSearch} = props;
    return (
        <Link to="/">
            <button className="close-search" onClick={onResetSearch}>
                Close
            </button>
        </Link>
    );
};

const getAll = [
    {
        title: "the book of RA",
        author: 'Robert Galbraith',
        imageLinks: {
            thumbnail:
                'https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcQK_a32ZoQ0mUQ8hHj0rS-ZXSoiA9ujpS1thED04xWG-l-G8bTB&usqp=CAU'
        },
        id: 'evuwdDLfAyYw',
        shelf: 'wantToRead',
    },
    {
        title: 'bahamut dragon god',
        author: 'Liaquat Ahamed',
        imageLinks: {
            thumbnail:
                'https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcSPNgP0LX5_1psjQracNJGJ_qhuFcK_uyf9cumzjEV_9qOsBBi0&usqp=CAU'
        },
        id: '74XNzF_al3Mr',
        shelf: 'wantToRead',
    },
    {
        title: 'Needful Things',
        author: 'Stephen King',
        imageLinks: {
            thumbnail:
                'http://books.google.com/books/content?id=jAUODAAAQBAJ&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api',
        },
        id: 'sdfsetdf23436457'
    },
    {
        title: 'Favorite flowers',
        author: 'Jasson Bold',
        imageLinks: {
            thumbnail:
                'https://books.google.com.bd/books/content?id=4WwdMJKXzhEC&printsec=frontcover&img=1&zoom=5&edge=curl&imgtk=AFLRE72fKVzWFza84ymTG8H0_IMOIuTetUqlNL6w0A3X5y5ZvvCId0OlhRD_4c_0v7HeL7mI0moCn9Z57UAJvjzwKRSDwefLEkZU0ZzG5upabVugka1PmiOfQR1EzBXXk2Z_1u491BcF',
        },
        id: 'sdf78233f',
        shelf: 'read'
    },
    {
        title: 'ReactJS',
        author: 'John Cavil',
        imageLinks: {
            thumbnail:
                'https://books.google.com.bd/books/content?id=ttc9b3N-Mv0C&printsec=frontcover&img=1&zoom=5&edge=curl&imgtk=AFLRE731dgcCtjtCbHqbggI4MXeLW_Goi6neR6SwPIp30YjG95TLKOL31Xmk_7OeLL0cmHpNBC2Mh1pmGF78HX14YfhNeY5CF_z_zFE1G2y5NfonUA5MAhChm-IJ116EYTHkJPdqwnxC',
        },
        id: 'iyiyoo233f',
        shelf: 'currentlyReading'
    }
];

class SearchBooksInput extends Component {

    state = {
        value: '',
        data: getAll
    };
    handleChange = event => {
        const val = event.target.value;
        this.setState({value: val});
        let books = this.state.data.filter(book => book.title.toLowerCase().indexOf(val.toLowerCase()) !== -1 || book.author.toLowerCase().indexOf(val.toLowerCase()) !== -1);
        this.props.onSearch(books);
    };

    render() {
        const {value, data} = this.state;

        return (
            <div className="search-books-input-wrapper">
                <input
                    type="text"
                    value={value}
                    placeholder="Search by title or author"
                    onChange={this.handleChange}
                />
            </div>
        );
    }
}

const SearchResults = props => {
    const {books} = props;
    return (
        <div className="search-books-results">
            <ol className="books-grid">
                {books?.map(book => (
                    <Book
                        key={book.id}
                        book={book}
                        shelf='none'

                    />
                ))}
            </ol>
        </div>
    );
};
export default BookshelfChanger;

Книга. js

import BookshelfChanger from "./BookshelfChanger";
import React from "react";

const Book = props => {

    const {book} = props;

    return (
        <li>
            <div className="book">
                <div className="book-top">
                    <div
                        className="book-cover"
                        style={{
                            width: 128,
                            height: 193,
                            backgroundImage: `url(${book.imageLinks.thumbnail})`
                        }}
                    />
                </div>
                <div className="book-title">{book.title}</div>
                <div className="book-authors">{book.author}</div>
            </div>
        </li>
    );
};

export default Book;

Приложение. js

import React from "react";
import ReactDOM from 'react-dom'
import BookshelfChanger from "./Book/BookshelfChanger";

class App extends React.Component {
    render() {
        return (
            <BookshelfChanger />
        );
    }
}

ReactDOM.render(<App/>, document.getElementById("root"));

export default App;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...