Реагировать на функцию поиска (фильтра), добавить параметр для поиска - PullRequest
0 голосов
/ 27 февраля 2020

**** РЕДАКТИРОВАТЬ ****: не должно быть так просто, как добавить: client.clientno.toLowerCase().indexOf(filter) !== -1 || client.id === filter? в функции submitFilter? Проблема здесь в том, что я получаю сообщение об ошибке «Ошибка типа: невозможно прочитать свойство 'toLowerCase' с нулевым значением (анонимная функция)

Я пытаюсь отредактировать полученную мной функцию поиска фильтра, но я не понимаю, куда добавить новый параметр для поиска или, если мне нужно деконструировать объект "клиент", чтобы искать более конкретно. Сейчас я могу искать только по client.text (это имя клиента), но я также хочу иметь возможность поиска по clientno ( номер клиента), который является не числом, а строкой, которая выглядит следующим образом: "C123456". Может кто-нибудь объяснить, где я должен добавить свой параметр client.clientno и как я могу фильтровать по этому параметру, не теряя фильтр по client.text?

мой код с «поисковым фильтром»: (Спасибо большое заранее за любую помощь!)

import React, {Component} from 'react';
import {Form, FormGroup, Input} from 'reactstrap';
import {StatusList} from './ClientList';
import {FormattedMessage, injectIntl} from 'react-intl';

class _SearchClientsContainer extends Component {
  constructor(props) {
    super(props);

    this.timer = null;

    this.state = {
      filter: null,
      clients: this.props.clients,
    };
  }

  changeFilter = event => {
    event.persist();
    clearTimeout(this.timer);
    this.setState({filter: event.target.value});
    this.timer = setTimeout(() => {
      this.submitFilter(event);
    }, 200);
  };


   submitFilter = event => { //<---------- my submit filter "search" function
     event.preventDefault();
     const filter = this.state.filter ? this.state.filter.toLowerCase() : '';
    const clients = filter.length === 0 ? this.props.clients : this.props.clients.filter(client => {
  return (


        client.text.toLowerCase().indexOf(filter) !== -1 || client.id === filter
 // <----- here I return the client.text and I need to filter by client.clientno as well which is a string that looks like this: C123456


      );
    });
    this.setState({clients});
  };

  render() {
    return (
      <>
        <div>
          <h3 className="mb-3">
             <FormattedMessage id="header.navbar.clientlist.title" />
          </h3>
           <Form className="mb-4" onSubmit={this.submitFilter}>
            <FormGroup>
               <Input
                 type="text"
                 placeholder={this.props.intl.formatMessage({id: 'header.navbar.clientlist.filter'})}
                 onChange={this.changeFilter}
               />
             </FormGroup>
           </Form>
         </div>
        <StatusList clients={this.state.clients} />
      </>
     );
    }
 }

 export const SearchClientsContainer = injectIntl(_SearchClientsContainer);

Я забыл упомянуть, вот как я отображаю список:

import React, {memo} from 'react';
import PropTypes from 'prop-types';
import {FormattedMessage} from 'react-intl';

const StatusItem = ({client}) => {
  return (
    <p className="mb-2 cursor-pointer" onClick={() => (window.location.href = client.viewLink)}>
      <strong>{client.text}</strong> {client.clientno && <span>({client.clientno})</span>}
    </p>
  );
};

StatusItem.propTypes = {
  client: PropTypes.object.isRequired,
};

const _StatusList = ({clients}) => {
  const favClients = clients.filter(c => c.favorite);
  const normalClients = clients.filter(c => !c.favorite);
  return (
    <div>
      <h3 className="mb-3">
        <FormattedMessage id="header.navbar.clientlist.favourites" />
      </h3>
      <div className="mb-4">
        {favClients.map(c => (
          <StatusItem client={c} key={c.id} />
        ))}
      </div>

      <h3 className="mb-3">
        <FormattedMessage id="header.navbar.clientlist.clients" />
      </h3>
      <div>
        {normalClients.map(c => (
           <StatusItem client={c} key={c.id} />
        ))}
       </div>
     </div>
   );
 };

 _StatusList.propTypes = {
   clients: PropTypes.arrayOf(PropTypes.object).isRequired,
 };

 export const StatusList = memo(_StatusList);

1 Ответ

1 голос
/ 27 февраля 2020

Для TypeError: Cannot read property 'toLowerCase' of null (anonymous function)

(client && client.toLowerCase().clientno ? client.clientno : '').toLowerCase().indexOf(filter) !== -1 || client.id === filter

Также вы можете фильтровать вот так

this.props.clients.filter(client => {
  return (
        client.text.toLowerCase().includes(filter)
        || client.clientno.toLowerCase().includes(filter)
        || client.id === filter
      );
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...