Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

218
Visualizações
almacene nombres de funciones en una matriz y llámelos uno por uno usando array.forEach()

Estoy construyendo un reactivo nativo que tiene casi 15 state para almacenar algunos datos. Ahora quiero almacenar todos estos valores (y recuperarlos todos) en/desde el almacenamiento interno, estoy usando react-native-mmkv .

 //functions from context api const {setUsername, setToken, setProgress} = useAppContext(); const getsettingsconfig = () => { const keys = storage.getAllKeys(); console.log(keys); // ['setProgress', 'setUsername', 'setToken'] keys.forEach(key => { const data = storage.getString(key); // I want to set all the values dynamically here key(parsedData); // setProgress(data), setUsername(data) etc. like this }); };

useAppContext.js

 import { createContext, useContext } from "react"; export const GlobalContext = createContext({}); export default function useAppContext() { return useContext(GlobalContext); }

Sin embargo, sigo recibiendo

 [TypeError: 'setProgress' is not a function]

¿Qué estoy haciendo mal aquí?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Esta es una forma posible de ejecutar una función cuyo nombre está presente en una matriz. El truco aquí es mapear el nombre de la función con la función misma (usando el objeto myObj ). Luego, uno simplemente accede al objeto con la clave y ejecuta la función (que es el valor correspondiente en el objeto myObj ).

 // declaring, defining 4 functions here // this may even be from useState - same will work const setField1 = d => console.log('setField1, data: ', d); const setField2 = d => console.log('setField2, data: ', d); const setField3 = d => console.log('setField3, data: ', d); const setField4 = d => console.log('setField4, data: ', d); // declaring an array of functions // this can be populated from local-storage - and it will work const fnArr = [setField1, setField2, setField3, setField4]; // for-each loop to execute each function in the array fnArr.forEach((fn, idx) => fn(idx)); // using a string array - which will not execute the functions console.log("\n\n can't execute strings as functions\n\n"); const strArr = ['setField1', 'setField2', 'setField3', 'setField4']; strArr.forEach(st => console.log(`'${st}' is a string & not a function... one can't execute it`)); // executing the same functions by using the string keys console.log('\n\n executing functions by using string-names as keys\n\n'); const myObj = Object.fromEntries(strArr.map((k, idx) => ([ k, fnArr[idx]]))); strArr.forEach((k, idx) => myObj?.[k](idx));
 .as-console-wrapper { max-height: 100% !important; top: 0 }

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda