reactjs React TS -返回使用上下文中的对象

lnlaulya  于 2023-04-20  发布在  React
关注(0)|答案(1)|浏览(111)

我创建了一个过滤器Context,因为我想将它与浏览页面分开。但我认为我做得不正确。我首先创建了如下类型和接口:

type Brand = {
    brand:string;
    checked:boolean;
}
type Gender = {
    gender: "Male" | "Female" | "Kids";
    checked:boolean;
}
type Shoes = {
    brand:Brand[];
    gender:Gender[];
}
interface FilterProvider {
    FilterState:()=>{},
    updateGenderState: (value: string)=>void,
    updateBrandState: (value: string)=>void,
}
interface FilterProviderProps{
    children: ReactNode,
}

在设置useContext之后

const FilterProvider = createContext({} as FilterProvider);

export const useFilterInfo = ()=>{
    return useContext(FilterProvider);
}

最后,返回如下:

export const FilterContext = ({children}: FilterProviderProps)=>{
    const [filterState,setFilterState] = useState<Shoes>({
        brand:[
            {
                brand:'New Balance',
                checked: false,
            },
            {
                brand:'Nike',
                checked: false,
            },
            {
                brand:'Addiddas',
                checked: false,
            },
            {
                brand:'Puma',
                checked: false,
            },
            {
                brand:'Converse',
                checked: false,
            },
            {
                brand:'Under Armour',
                checked: false,
            },
        ],
        gender:[{
            gender:'Male',
            checked:false,
        },
        {
            gender:'Female',
            checked:false,
        },
        {
            gender:'Kids',
            checked:false,
        }
    ],
    });

    const FilterState = ()=>{
        return filterState;
    }
    const updateGenderState = (value: string)=>{

    }
    const updateBrandState = (value: string)=>{

    }
    
    return  <FilterProvider.Provider value={{FilterState,updateBrandState,updateGenderState}}>
                {children}
            </FilterProvider.Provider>

}

我遇到的问题是,当我尝试控制台记录filterState对象时,它什么也没有返回。我想我有wring返回类型,如果有人可以帮助的话。谢谢,我知道代码有点长,但我不想遗漏任何人们会要求的东西。在过滤器文件中,我这样调用它:

import { useFilterInfo } from '../context/FilterContext'

export const Filter = (props:FilterProps)=>{
    const {FilterState,updateBrandState,updateGenderState} = useFilterInfo();
    console.log(JSON.stringify(FilterState));
...(rest of code)
nhhxz33t

nhhxz33t1#

问题是FilterState是一个function,但你期望的是一个object,正如我从代码中看到的:

const {FilterState,updateBrandState,updateGenderState} = useFilterInfo();
console.log(JSON.stringify(FilterState));

您必须调用FilterState()(因为它是一个函数)才能返回对象。

相关问题