Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
52 views
in Technique[技术] by (71.8m points)

javascript - Mapping an array in React uses values of previous render

I am building a custom hook for react, which applies filter(by category) and search to an array.

const amountSmallestFirst = (a, b) => {
  return a.amount - b.amount;
};

const amountLargestFirst = (a, b) => {
  return b.amount - a.amount;
};

const alphabeticallySorted = (a, b) => {
  if (a.name < b.name) {
    return -1;
  }
  if (a.name > b.name) {
    return 1;
  }
  return 0;
};

const alphabeticallySortedReverse = (a, b) => {
  if (a.name > b.name) {
    return -1;
  }
  if (a.name < b.name) {
    return 1;
  }
  return 0;
};

const useSearchAndFilter = (data: any, isLoading: boolean, sortBy: SortBy) => {
  const [search, setSearch] = useState<string>('');
  const [currentFilter, setFilter] = useState<SortBy>(sortBy);
  const [result, setResult] = useState<any>([]);

  const handleSearch = (event: React.FormEvent<HTMLInputElement>) => {
    const target = event.target as HTMLInputElement;
    setSearch(target.value);
  };

  const selectSorting = (sortBy = SortBy.AMOUNT_LARGEST_FIRST) => {
    switch (sortBy) {
      case 'AMOUNT_SMALLEST_FIRST':
        return amountSmallestFirst;
      case 'AMOUNT_LARGEST_FIRST':
        return amountLargestFirst;
      case 'ALPHABETICALLY_SORTED':
        return alphabeticallySorted;
      case 'ALPHABETICALLY_SORTED_REVERSE':
        return alphabeticallySortedReverse;
      default:
        return amountLargestFirst;
    }
  };

  const applySearchAndFilter = (data: any, sortBy = SortBy.AMOUNT_LARGEST_FIRST) => {
    if (!data) return null;
    let results;
    if (search !== '') {
      results = data.filter(({ name }: Name) => name.toLowerCase().includes(search.toLowerCase()));
    }
    const isNumber = parseInt(search);
    if (isNumber) {
      results = data.filter(({ amount }: Name) => amount === isNumber);
    }
    if (!results) {
      results = data;
    }
    results.sort(selectSorting(sortBy));
    setResult(results);
  };

  useLayoutEffect(() => {
    applySearchAndFilter(data, currentFilter);
  }, [isLoading, search, currentFilter]);

  return { result, search, setFilter, handleSearch, currentFilter };
};

export { useSearchAndFilter };

It works fine when I search something, but when the search is not enabled the filtering works one step behind. I started debugging the problem by tracking when the array changes and came across some strange behavior: the data is working untill I start mapping the array to smaller components.

  console.log(nameList);
  const mapListItems = nameList.map((item: Name, i: number) => {
    console.log(item, nameList);
    return <ListItem key={item.name} item={item} color={i % 2 === 0 ? 'secondary' : 'primary'} />;
  });

The nameList logs are both identical and the updated array, but the props passed to the component are information of previous render's array?

How is this possible and how situations like this can be fixed?

I've tried to implement callback functions and useEffect&useLayout hooks, but both failed.

Edit:

Baymax requested on setFilter implementation

import React, { useState, useEffect, useLayoutEffect } from 'react';
import { ReactComponent as OpenIcon } from '../assets/open.svg';
import { SortBy } from '../types';
import Togglable from './Togglable';

interface FilterProps {
  setFilter: any;
  currentFilter: SortBy;
}

const Filter: React.FC<FilterProps> = ({ setFilter }) => {
  const [show, setShow] = useState<boolean>(false);
  const [current, setCurrent] = useState<SortBy | null>(SortBy.AMOUNT_LARGEST_FIRST);

  useLayoutEffect(() => {
    setFilter(current);
    setShow(false);
  }, [current]);

  const handleFilterChange = (value: SortBy) => {
    setCurrent(value);
  };

  return (
    // Relative parent needed for the togglable selection which is absolute
    <div className='relative'>
      <div
        className='m-w-30 h-11 px-3 bg-gray-800 text-white flex rounded-lg justify-between items-center flex-nowrap space-x-2 cursor-pointer'
        onClick={() => setShow(!show)}
      >
        <p className='flex-none'>Filter by</p>
        <OpenIcon className={`w-3 fill-current transition duration-300 linear text-white ${show ? 'arrowDown' : 'arrowUp'}`} />
        <Togglable show={show}>
          <ul className='bg-gray-800 absolute text-gray-300 -h-full mt-6  w-full -m-5 z-10 rounded-lg sm:w-48 sm:-ml-28'>
            <li
              className={`p-2  hover:text-white rounded-t-lg ${current === SortBy.AMOUNT_LARGEST_FIRST && 'bg-gray-700'} `}
              onClick={() => handleFilterChange(SortBy.AMOUNT_LARGEST_FIRST)}
            >
              Highest amount first
            </li>
            <li
              className={`p-2 hover:text-white ${current === SortBy.AMOUNT_SMALLEST_FIRST && 'bg-gray-700'}`}
              onClick={() => handleFilterChange(SortBy.AMOUNT_SMALLEST_FIRST)}
            >
              Lowest amount first
            </li>
            <li
              className={`p-2 hover:text-white ${current === SortBy.ALPHABETICALLY_SORTED && 'bg-gray-700'}`}
              onClick={() => handleFilterChange(SortBy.ALPHABETICALLY_SORTED)}
            >
              Alphabetically sorted
            </li>
            <li
              className={`p-2 hover:text-white rounded-b-lg ${current === SortBy.ALPHABETICALLY_SORTED_REVERSE && 'bg-gray-700'}`}
              onClick={() => handleFilterChange(SortBy.ALPHABETICALLY_SORTED_REVERSE)}
            >
              Alphabetically reversed
            </li>
          </ul>
        </Togglable>
      </div>
    </div>
  );
};

export default Filter;

Solution:

For some reason passing API-data directly to results resulted into a bug in sorting.

    if (!results) {
      results = data;
    }

After passing a copy of the data to results, the sorting started working.

    if (!results) {
      results = [...data];
    }

This is really strange for me, since the [...data] and data are identical when console.logged.

question from:https://stackoverflow.com/questions/65857638/mapping-an-array-in-react-uses-values-of-previous-render

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...