大家好,请帮帮我当尝试在对象数组中查找值时,我得到一个错误
属性'item'在类型'object'上不存在
in lineel =>el.item
如何解决这个问题
const heroArray = useAppSelector((state) => state.heroList.items)
const addHero = (item:string, index:number):void => {
const elements = {
id,
item
}
dispatch(addItem(elements))
const b = heroArray.find(el => el.item === 'geovishap-hatchling')
}
types/redux toolkit slice
interface HeroList {
items: object[];
elements: {
id: string | undefined;
item: string;
}
}
const initialState: HeroList = {
items: [],
elements: {
id:'',
item:'',
}
}
export const heroListSlice = createSlice({
name: 'heroList',
initialState,
reducers: {
addItem: (state, action: PayloadAction<Object>) => {
state.items.push(action.payload)
localStorage.setItem('items', JSON.stringify(state.items));
},
},
})
在你的界面中有" element ":{…} make element: SomeInterface。创建另一个接口,为元素结构定义该接口。
{
id:string,
item:string
}
像这样
interface HeroListElements {
id: string; // I would drop this -> | undefined
item: string;
}
interface HeroList {
items: object[]; // <- I would not use object
elements: HeroListElements
}
const initialState: HeroList = {
items: [],
elements: {
id: '',
item: ''
}
}
不使用object
作为对象。TS中的object
表示类对象元素
const f: object = [];
在您的情况下,您需要定义类型Hero
并使用它来代替object
type Hero = {
id: string,
item: string
}
interface HeroList {
items: Hero[];
elements: {
id: string | undefined;
item: string;
}
}
更改行
const elements = {
id,
item
}
const elements = {
id:index,
item
}
因为你在函数参数
中通过索引引用id