ReactJs - Фильтр поиска с Object.keys (). Map - Uncaught TypeError: this.state.texts.filter не является функцией в t.value - PullRequest
0 голосов
/ 27 июня 2018

Попытка создать простой фильтр поиска. Таблица элементов будет отфильтрована по значению поля ввода. Вот соответствующая часть компонента ... к сожалению, я получаю ошибку: Uncaught TypeError: this.state.texts.filter не является функцией в t.value

Есть идеи, в чем проблема? Это потому что я сопоставляю ключи? Большое спасибо за помощь!

    import React from 'react';
    import TextCardInTable from './TextCardInTable';


    const textsFileName = 'texts3.json'

    class Search extends React.Component {

      constructor(props) {
        super(props);

        this.state = {
            search: '',
            texts: [],
          };
      }

      componentWillMount() {
        this.fetchData();
      }

      fetchData() {
        this.setState({ isLoading: true })
        const options = { decrypt: false }
        getFile(textsFileName, options)
          .then((file) => {
            var texts = JSON.parse(file || '[]')
            this.setState({
              texts: texts,   
            })
          })
          .finally(() => {
            this.setState({ isLoading: false })
          })


          }

    updateSearch(event) {
       this.setState({search: event.target.value});
    }

    render () {
         let filteredTexts = this.state.texts.filter(
           (text) => {
             return text.title.indexOf(this.state.search) !== -1;
           }
         );
         return (
           <div>
               <input type="text"
                 value={this.state.search}
                 onChange={this.updateSearch.bind(this)}
                />

                {Object.keys(filteredTexts).map(key =>
                  <TextCardInTable
                   textprops={this.state.texts[key]}
                  />
                 )}   

            </div>
          )
      }

Снимок экрана из console.log (тексты): enter image description here

1 Ответ

0 голосов
/ 28 июня 2018

На основании скриншота, texts - это объект, где каждый «текст» представлен как свойство, что-то вроде этого:

{
  text123: {
    author: "a1",
    title: "t1",
    ...
  },
  text456: {
    author: "a2",
    title: "t2",
    ...
  },
  ...
}

Если вы хотите отфильтровать эти «текстовые» элементы на основе их свойства title, вы можете использовать Object.values, чтобы превратить ваш объект в массив, где вы можете выполнить фильтрацию, например ::

Object.values(texts) // -> [{author: "a1", title: "t1"}, {author: "a2", title: "t2"},... ]
      .filter(text => text.title.indexOf(this.state.search) !== -1 ) 
...