ค้นหาเว็บไซต์

reactjs - วิธีส่งอาร์เรย์และ setArray ในค่าของ provider (React, Typescript, Context)


ฉันจะส่งอาร์เรย์และตั้งค่าอาร์เรย์ในค่าของผู้ให้บริการได้อย่างไร ปัญหาหลักของฉันคือวิธีสร้างอินเทอร์เฟซสำหรับสิ่งนี้ เพราะมันบอกว่าประเภทไม่ถูกต้อง

อาร์เรย์ประกอบด้วยออบเจ็กต์ List และฉันต้องการตรวจสอบอาร์เรย์นี้และตั้งค่าเพื่อใช้ตัวกรองในภายหลัง

import React from "react";

interface Lista {
  nome: string,
  empresa: string,
  ramal: number
}

const listaInicial: Lista = {
  nome: "",
  empresa: "",
  ramal: 0
}

interface Props {
  children: React.ReactNode
}

const ListaContext = React.createContext<Lista>(listaInicial);

export default function ListaProvider({children}: Props) {
  const [lista, setLista] = React.useState<Lista[]>([]);

  React.useEffect(() => {
    setLista([
      {
        nome: "nome 1",
        empresa: "matriz",
        ramal: 2000
      },
      {
        nome: "nome 2",
        empresa: "matriz",
        ramal: 2001
      },
      {
        nome: "nome 3",
        empresa: "sede",
        ramal: 2002
      },
      {
        nome: "nome 4",
        empresa: "sede",
        ramal: 2002
      },
    ])
  }, []);

  return (
    <ListaContext.Provider value={{lista, setLista}}>
      {children}
    </ListaContext.Provider>
  )
}

คำตอบ #1

คุณจำเป็นต้องสร้างอินเทอร์เฟซที่แตกต่างสำหรับ React.createContext

ตัวอย่างเช่น:

    interface ListaContextValue {
     lista:Lista[],
     setLista:(data:Lista[]) => void
    }

    const listaInicial: ListaContextValue = {
      lista:[
       {nome: "",
        empresa: "",
        ramal: 0
       }],
      setLista: (data) => {}
    }

แล้วก็,

const ListaContext = React.createContext<ListaContextValue>(listaInicial);

คำตอบ #2

React.createContext<Lista>(listaInicial); หมายความว่าค่าที่คืนกลับของ ListaContext.Provider เป็นชนิด Lista ถ้าคุณต้องการตั้งค่าของโปรไวเดอร์เป็น lista และ setLista คุณสามารถลองวิธีนี้โดยไม่ต้องกำหนดชนิดสำหรับ createContext

const ListaContext = React.createContext(listaInicial);

หรือ

const ListaContext = React.createContext<{lista: Lista[], setLista:React.Dispatch<React.SetStateAction<Lista[]>> }>(listaInicial);

บทความที่เกี่ยวข้อง