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

90
Visualizações
React Native how to pass a function with a parameter inside a for-loop

I have the code below for a React Native app using Javascript and Im creating an array of objects that are data for a context menu.

When the user selects a project from the menu it should call handleSelectedProject which it does and pass the selected project object but I get undefined for the project variable.

Any ideas what the syntax should be to get the selected project object.

Thanks in advance.

export default MobileMenu = () => {
  const projects = useSelector(getPickerList);
  const [menuItems, setMenuItems] = useState([]);

  useEffect(() => {
    loadMenuItems();
  }, [projects]);

  const handleNewProject = () => {
    console.info("New Project");
  };

  const handleSelectedProject = (project) => {
    console.info("Project...", project);
  };

  const loadMenuItems = () => {
    let items = [];

    items.push({
      label: "New Project",
      onPress: handleNewProject,
      seperator: false,
    });

    items.push({ seperator: true });

    for (var i = 0; i < projects.length; i++) {
      items.push({
        label: projects[i].project_name,
        onPress: () => handleSelectedProject(projects[i]),
        seperator: false,
      });
    }

    setMenuItems(items);
  };

  return (
    <ScrollView>
      <View style={styles.container}>
        <ContextMenu items={menuItems} />
      </View>
    </ScrollView>
  );
};
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The problem is with your for loop. The onPress callback will reference the loop variable when the loop is already finished, at which time i is out of range, so projects[i] will evaluate to undefined.

The easy solution is to use a block scoped variable i, so that projects[i] really references the variable that was created for that loop's iteration specifically. You do this by replacing var i with let i.

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