next.js 类型“UserContextType”不是数组类型

uplii1fm  于 2023-06-05  发布在  其他
关注(0)|答案(1)|浏览(182)

我在React中遇到了一些上下文问题。我正在尝试将对象设置为状态。它在本地工作,但当我尝试构建项目时,我得到一个错误:类型“UserContextType”不是数组类型。
我不知道为什么我得到这个错误,因为我没有试图使用它作为一个数组的任何地方。
以下是上下文文件:

import React, {
  useState,
  Dispatch,
  SetStateAction,
  createContext,
} from "react";

type Props = {
  children: JSX.Element;
};

type Filters = {
  type: string[];
  rating: number[];
  facilities: string[];
  stars: number[];
  minPrice: number;
  maxPrice: number;
};

type UserContextType = {
  filters: Filters;
  setFilters: Dispatch<SetStateAction<Filters>>;
};

const iUserContextState = {
  filters: {
    type: [],
    stars: [],
    rating: [],
    facilities: [],
    minPrice: 0,
    maxPrice: 0,
  },
  setFilters: () => {},
};

export const FilterContext = createContext<UserContextType>(iUserContextState);

export function FilterComponent({ children }: Props) {
  const [filters, setFilters] = useState<Filters>({
    type: [],
    stars: [],
    rating: [],
    facilities: [],
    minPrice: 0,
    maxPrice: 0,
  });
  return (
    <FilterContext.Provider value={{ filters, setFilters }}>
      {children}
    </FilterContext.Provider>
  );
}

export default FilterComponent;

这是我的过滤器组件中的函数,我在其中使用了这段状态

function Filter({}: Props) {
  const [filters, setFilters] = useContext(FilterContext);
  const [filteredItems, setFilteredItems] = useState([]);
  const [smallestPrice, setSmallestPrice] = useState<number>();
  const [highestPrice, setHighestPrice] = useState<number>();

  const listFunction = (e: React.FormEvent<HTMLUListElement>) => {
    const listItem = e.target as Element;
    const parentList = listItem.closest(".filter-list__item");

    const filterList = Array.from(
      parentList.querySelectorAll("li.filter__item")
    );

    const newArray = filterList
      .filter((item) => item.querySelector("input:checked"))
      .map((item) => item.querySelector("input").id);

    if (parentList.classList.contains("js-type")) {
      setFilters((prevState) => ({ ...prevState, type: newArray }));
    }

    if (parentList.classList.contains("js-rating")) {
      setFilters((prevState) => ({ ...prevState, rating: newArray }));
    }

    if (parentList.classList.contains("js-facilities")) {
      setFilters((prevState) => ({ ...prevState, facilities: newArray }));
    }
    if (parentList.classList.contains("js-stars")) {
      setFilters((prevState) => ({ ...prevState, stars: newArray }));
    }
  };

  const openFunction = (e: React.MouseEvent<HTMLButtonElement>) => {
    const target = e.target as Element;
    const filterTitle = target.parentNode;
    const filter = filterTitle.parentNode;

    filter.classList.toggle("is-open");
  };

非常感谢!

6za6bjd0

6za6bjd01#

变更:

const [filters, setFilters] = useContext(FilterContext);

收件人:

const {filters, setFilters} = useContext(FilterContext);

相关问题