typescript 如何从筛选数组中获取每个项,而不对每个项使用Map

5vf7fwbs  于 2022-12-19  发布在  TypeScript
关注(0)|答案(1)|浏览(104)

我取一个数组并在上下文中过滤值:

const { responsible } = useResponsible()
const [ids, setIds] = useState([])

const filteredResponsible = responsible?.filter((resp) =>
    ids.includes(resp.id)
  )

问题是我需要创建一个Map来一个接一个地获取每个id对应的值,这会导致代码过长:

const { filteredResponsible } =  useResponsible

 const responsibleName =  filteredResponsible.map((resp) => resp.name)

 const responsibleEmail =  filteredResponsible.map((resp) => resp.email)

 const responsibleAddress =  filteredResponsible.map((resp) => resp.address)
     ...

And so on with each item in the array.

我使用React Hook窗体的setValue来设置输入中的值:

useEffect(() => {
    setValue('name', `${responsibleName}`)
    setValue('email', `${responsibleEmail}`)
    setValue('address', `${responsibleAddress}`)
    setValue('cep', `${responsibleCep}`)
    setValue('district', `${responsibleDistrict}`)
    setValue('city', `${responsibleCity}`)
    setValue('state', `${responsibleState}`)
    setValue('phone', `${responsiblePhone}`)
    setValue('sex', `${responsibleSex}`)
  }, [])

我怎样才能使这些Map更小?而不必创建Map来获取数组中的每一项?

bfnvny8b

bfnvny8b1#

似乎没有任何理由在每次渲染时执行这些map调用,也没有必要在需要它们的地方以外的任何地方执行这些调用,因为您只展示了在仅挂载效果中使用结果。

const { filteredResponsible } = useResponsible; // Is there really no `()` needed here?

useEffect(() => {
    setValue("name", `${filteredResponsible.map(({name}) => name)}`);
    setValue("email", `${filteredResponsible.map(({email}) => email)}`);
    setValue("address", `${filteredResponsible.map(({address}) => address)}`);
    // ...
}, []);

如果你真的需要在每个渲染中使用这些不同的数组,除非你可以改变你的数据结构,使其更适合你的输出,否则我不认为你有很多选择。

const { filteredResponsible } =  useResponsible; // ()?

const responsibleName = [];
const responsibleEmail = [];
const responsibleAddress = [];

for (const { name, email, address } of filteredResponsible) {
    responsibleName.push(name);
    responsibleEmail.push(email);
    responsibleAddress.push(address);
}

如果情况确实如此,您可能希望避免在每次渲染时都这样做:

const { filteredResponsible } = useResponsible; // ()?

const { responsibleName, responsibleEmail, responsibleAddress } = useMemo(() => {
    const responsibleName = [];
    const responsibleEmail = [];
    const responsibleAddress = [];
    for (const { name, email, address } of filteredResponsible) {
        responsibleName.push(name);
        responsibleEmail.push(email);
        responsibleAddress.push(address);
    }
    return { responsibleName, responsibleEmail, responsibleAddress };
}, [filteredResponsible]);

相关问题