【问题标题】:How to return the original state after a search filter function has been cleared in redux store redux在redux store redux中清除搜索过滤器功能后如何返回原始状态
【发布时间】:2020-12-01 03:24:34
【问题描述】:

我有一个我想实现的搜索和过滤功能,用户将搜索项目,它们将在平面列表中返回,当用户清除搜索框或搜索框为空时,我希望初始状态为被退回。

我试过这个: 该功能确实过滤了商店,但是当我清除它时,原始状态项不再存在。返回的是搜索值

    search: (state, { payload }) => {
      const itemsToFilter = state.filter((item) => {
        let itemLowerCase = item.item_description.toLowerCase();

        let searchItemToLowerCase = payload.item_description.toLowerCase();

        return itemLowerCase.indexOf(searchItemToLowerCase) > -1;
      });

      if (payload.item_description.length !== 0) {
        return itemsToFilter;
      } else {
        return state;
      }
    },

这是我的组件函数

import {useDispatch, useSelector} from 'react-redux';

  const [searchValue, setSearchValue] = useState("");
  
  const items = useSelector(state => state.items)
  const dispatch = useDispatch()

  const searchItems = (e) => {
    const text = e.nativeEvent.text;
    setSearchValue(text);

    dispatch(
      searchItemAction({
        item_description: searchValue,
      })
    );
  };

<TextInput value={searchValue} onChange={searchItems} />

【问题讨论】:

  • “原始状态项目”应该是什么?如果您需要保留一组原始项目,最好将它们保存为静态数据并在某些操作时调用它。

标签: reactjs react-native redux redux-toolkit


【解决方案1】:

首先,useState() 是异步的,因此您的调度使用旧字符串。

  const searchItems = (e) => {
    const text = e.nativeEvent.text;
    setSearchValue(text); // Will be updated async

    dispatch(
      searchItemAction({
        item_description: searchValue, //searchValue will still be the old search value
      })
    );
  };

简单的解决方案是使用text 变量:

  const searchItems = (e) => {
    const text = e.nativeEvent.text;
    setSearchValue(text);

    dispatch(
      searchItemAction({
        item_description: text,
      })
    );
  };

另外,您将原始数据存储在哪里?你应该创建一个选择器,这样就可以了。

我认为最好的解决方案是仅在此组件中使用选择器(如果您在其他任何地方都不需要它):

const [searchValue, setSearchValue] = useState("");

const items = useSelector(state => {
  if(searchValue.length === 0) {
    return state.items;
  }
  return state.items.filter((item) => {
    let itemLowerCase = item.item_description.toLowerCase();
    let searchItemToLowerCase = searchValue.toLowerCase();
    return itemLowerCase.indexOf(searchItemToLowerCase) > -1;
  });
}

const searchItems = (e) => {
  const text = e.nativeEvent.text;
  setSearchValue(text);
};

否则您需要将搜索字符串存储到 redux 并使用存储的字符串在选择器中进行过滤。

【讨论】:

  • 如果我知道你是谁......我会为你买最好的苏格兰威士忌之一,我在过去的 6 天里一直在。您的解决方案有效,而且非常简单。我试过使用useSelector 来搜索和过滤猜测我以错误的方式实现它。非常感谢。
猜你喜欢
  • 2017-07-12
  • 1970-01-01
  • 2019-07-04
  • 1970-01-01
  • 2017-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多