I have a state and use it as an index into an array of objects. When I pass that object as a prop to other component. Even with the check, it gives the error:
import React, { Dispatch, useState } from 'react'; import { TestingTwo } from './TestingTwo'; interface Menu { ItemNumber?: number; ItemString?: string; setState?: Dispatch<React.SetStateAction<number>>; } export const TestingPage = () => { const [activeMenu, setActiveMenu] = useState<number>(1); const [something, SetSomething] = useState<number>(0); const TestMenu: Menu[] = [ { ItemNumber: 1, ItemString: 'test', setState: SetSomething, }, ]; return ( <> {TestMenu && TestMenu[activeMenu] && TestMenu[activeMenu].ItemNumber ? ( <TestingTwo number={TestMenu[activeMenu].ItemNumber || 0} OnClick={() => TestMenu[activeMenu].setState(1)} //Cannot Invoke an object which is possibly 'undefined' /> ) : null} </> ); };
Components:
interface TestingTwoProps { number: number; OnClick: () => void; } export const TestingTwo = ({ number, OnClick }: TestingTwoProps) => { return <>{number}</>; };
P粉6429205222024-04-04 12:28:17
Here are three solutions:
Update the number type in TestingTwo
to number | undefined.
Another solution is:
(Recommended if you know you will always need the number) Update your interface from:
interface menu { ItemNumber?: number;Item string? : string; }
to:
Interface menu {ItemNumber: number;Item string? : String; }
Remove optional on ItemNumber ?
Update second question
You also encounter the same problem in setting the status, the interface makes it an optional field.
You can make it required by removing ?
OnClick={() => TestMenu[activeMenu]?.setState()
< Updated to check if setState exists question mark< 更新为检查 setState 是否存在的问号
Final Edit
To get the last bit, you just add the following:
OnClick={() => TestMenu[activeMenu]?.setState(1)
The reason for the error is that you are not passing a value to setState