search

Home  >  Q&A  >  body text

React: Using state as index into array of objects returns undefined despite checking

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粉481035232P粉481035232232 days ago360

reply all(1)I'll reply

  • P粉642920522

    P粉6429205222024-04-04 12:28:17

    Here are three solutions:

    1. Update the number type in TestingTwo to number | undefined.

    2. Another solution is:

    3. (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.

    1. You can make it required by removing ?

    2. 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

    reply
    0
  • Cancelreply