reactjs redux工具包useSelector()在循环内

r8xiu3jd  于 2022-12-22  发布在  React
关注(0)|答案(2)|浏览(188)

所以我有2个redux状态和选择器,它们工作得很好。但是我想在map()循环中调用第二个选择器(获取基于www.example.com的详细列表category.id)。我该怎么做呢?

const Dashboard = () => {
  const [data, setData] = useState([]);
  const categories = useSelector(viewFinalCategories);
  // categories is loaded well
  
  const createFinalData = () => {
    const finalData = categories.map((category) => {
      return {
        title: category.label,
        category: category,
        data: useSelector(viewInventoriesByCategory(category.id)), // <- error hook cannot called here..
      };
    });
    setData(finalData);
  };

  useEffect(() => {
    createFinalData();
  }, [categories]);

  return (
     // SectionList of RN here...
  )
k7fdbhmy

k7fdbhmy1#

因为它违反了钩子规则,所以不能在函数内部调用useSelector
解决方案是在组件级别获取数据,并在函数内部进行过滤

const {inventories} = useSelector(state => state)

 const createFinalData = () => {
    const finalData = categories.map((category) => {
      return {
        title: category.label,
        category: category,
        data: inventories.filter((item) => item.idCategory === idCategory)
      };
    });
    setData(finalData);
  };
yi0zb3m4

yi0zb3m42#

useSelector是一个钩子,它必须遵循钩子规则,其中之一是它不能在循环中使用。作为替代,你需要将所有这些逻辑从组件移到另一个选择器。在这种情况下,我将使用createSelector from reselect,因为你可以将选择类别组合到新创建的selectFinalData中:

import { createSelector } from 'reselect'

const selectFinalData = () =>
  createSelector(
    viewFinalCategories,
    (state, categories) => categories.map((category) => ({
      title: category.label,
      category: category,
      data: viewInventoriesByCategory(category.id)),
     })
    )
  )

并将其用于组件:

const finalData = useSelector(selectFinalData())
setData(finalData);

相关问题