我正在尝试根据状态有条件地渲染一些卡片项目。我在一个NextJS 13项目建设像一个12。
typescript 版本是:“5.2.2”
它抛出了这个错误,我不明白为什么:类型“ContextProps”上不存在属性“filter”。
顺便说一句..
代码如下:
EntryContext.tsx:
import { createContext, useReducer, useContext } from 'react';
import { entriesReducer } from './';
import { Entry } from '../../interfaces';
import { generateId } from '../../utils';
export type ContextProps = {
entries: Entry[]
}
export type EntriesState = {
entries: Entry[]
}
const ENTRIES_INITIAL_STATE: EntriesState = {
entries: [
{
_id: generateId(),
description: 'Esto es una prueba',
createdAt: Date.now().toString(),
status: 'Pending'
},
{
_id: generateId(),
description: 'Esto es una prueba',
createdAt: (Date.now() - 10000).toString(),
status: 'In-progress'
},
{
_id: generateId(),
description: 'Esto es una prueba',
createdAt: (Date.now() - 100000).toString(),
status: 'Finished'
},
]
}
export const EntriesContext = createContext<ContextProps>({
entries: []
})
export const EntriesProvider = (
{
children
}: {
children: React.ReactNode
}): JSX.Element => {
const [state, dispatch] = useReducer(entriesReducer, ENTRIES_INITIAL_STATE)
return (
<EntriesContext.Provider value={{
...state
}}>
{children}
</EntriesContext.Provider>
)
}
export const useEntries = () => useContext(EntriesContext)
问题就在这里,在渲染器常数中
EntryList.tsx:
import { List, Paper } from "@mui/material"
import { EntryCard } from "./EntryCard"
import { Entry, Status } from "../../interfaces"
import { useEntries } from "../../context/entries"
type Props = {
status: Status
}
export const EntryList = ({ status }: Props): JSX.Element => {
const entries = useEntries()
const renderEntries = entries
.filter((entry: Entry) => entry.status === status)
.map((entry: Entry) => (
<EntryCard
key={entry._id}
entry={entry}
/>
))
return (
<div
>
<Paper
sx={{
height: 'calc(100vh - 160px)',
overflowY: 'auto',
backgroundColor: 'transparent',
padding: 1,
}}
>
<List
sx={{
opacity: 1
}}
>
</List>
</Paper>
</div>
)
}
1条答案
按热度按时间tyky79it1#
您的上下文是一个具有
entries
属性的对象当你写
const entries = useEntries()
。entries
的类型是{entries: []}
,你不能过滤对象(entries.filter
)。您可以通过以下方式解决此问题:
1.从上下文中解构条目
1.挂钩结构
1.将数组而不是对象传递给上下文