Jak przekazać talicę obiektów do komponentu?

Jak przekazać talicę obiektów do komponentu?
A2
  • Rejestracja: dni
  • Ostatnio: dni
  • Postów: 42
0

hej
Jestem nowy w typescript i mam taki banalny blad.

Kopiuj
(property) data: menuItems[]
Type '{ data: menuItems[]; }' is not assignable to type 'IntrinsicAttributes & menuItems[]'.
  Property 'data' does not exist on type 'IntrinsicAttributes & menuItems[]'.ts(2322)

Tutaj jest kod:
https://codesandbox.io/s/data-is-not-a-function-ju21g6?file=/src/Settings.tsx

A tutaj jest chyba powiązany z tym bledem kolejny
https://codesandbox.io/s/data-is-not-a-function-ju21g6?file=/src/TreeSettings.tsx:256-320

Kopiuj
interface menuItems {
  name: string;
  level: number;
  id: number;
  pid: number;
  children?: any[];
}

const Settings = () => {
  const { flattenarr, zerotreetoarr } = useConvertTree();
  const [data, setData] = useState<menuItems[]>([]);
  useEffect(() => {
    zerotreetoarr(tree.children as [], [0]);
    // eslint-disable-next-line react-hooks/exhaustive-deps
    setData(flattenarr);
  }, []);
  return <TreeSettings data={data} />;
};
Kopiuj
 interface menuItems {
  name: string;
  level: number;
  id: number;
  pid: number;
  children?: any[];
}
 interface treeItems {
  name: string;
  children: treeItems[];
}
Kopiuj
const TreeSettings = (data: menuItems[]) => {
  return (
    <>
      {data.map((t) => {
        return <div>{t.name}</div>;
      })}
    </>
  );
};
Xarviel
  • Rejestracja: dni
  • Ostatnio: dni
  • Postów: 847
1
artur2015 napisał(a):
Kopiuj
const TreeSettings = (data: menuItems[]) => {

Jeśli przekazujemy dane do komponentu to tam wszystkie wartości są widoczne w formie obiektu

Kopiuj
const TreeSettings = (props) => {
  console.dir(props); // <-- dodatkowy obiekt, o który mi chodzi
  console.dir(props.data); // <-- nasza wartość, która też może być obiektem
  console.dir(props.data.foo); // <-- i finalnie jakaś przykładowa właściwość
  
  // ...
}

<TreeSettings data={data} />

Możemy skorzystać tutaj z destrukturyzacji, żeby pominąć jeden obiekt

Kopiuj
const TreeSettings = ({ data }) => {
  console.dir(data);
  console.dir(data.foo);
  
  // ...
}

I tutaj przechodzimy już do sedna, czyli połączenia tego z TypeScript :D

Możemy wykorzystać typ VC, który udostępnia nam React

Kopiuj
import type { VC } from 'react';

interface MenuItems {
  // ...
}

interface TreeSettingsProps {
  data: MenuItems[];
}

const TreeSettings: VC<TreeSettingsProps> = ({ data }) => {
  // ...
}

Zarejestruj się i dołącz do największej społeczności programistów w Polsce.

Otrzymaj wsparcie, dziel się wiedzą i rozwijaj swoje umiejętności z najlepszymi.