简体   繁体   中英

ReactJS: Function run multiple times without being called

Is there any reason a function in a react component would run multiple times although it is being invoked only once?

I have this test function that auto-invokes itself as in:

  let xfunction = (() =>
   {
     console.log('test');
   }
  )();

This is what I get in the console:

在此处输入图片说明

App.js Source Code:

import React, { useState, useEffect } from 'react';
import { getAllPokemons } from './services/pokemon'
import './App.css';
function App() {


  const [pokemonData, setPokemonData] = useState([]);
  const [loading, setLoading] = useState(true);
  const initialUrl = 'payload.json'


  useEffect(() => {
    async function fetchData() {
      let response = await getAllPokemons(initialUrl);
      console.log(response);
      await loadingPokemon(response.pokemon);
      setLoading(false);
    }
    fetchData();

  }, [])

  const loadingPokemon = async (data) => {
    let _pokemon = await Promise.all(data.map(async pokemon => {
      return pokemon;
    })
    );
    setPokemonData(_pokemon);
  }




  // Start - Filter by Pokemon Type
  let pokemonTypes = (() =>
   {
    console.log('test');
   }

  )();



// End - Filter by Pokemon Type

  return (

    <div></div>

  );


}

export default App;

The function is not being called or references anywhere else!

Thanks!

Solution as proposed by @Jared Smith:

If you do not want your functions rerendered and you are using react hooks, please include them in the useEffect hook as in:

  useEffect(() => {
    async function fetchData() {
      let response = await getAllPokemons(initialUrl);
      await loadingPokemon(response.pokemon);
      setLoading(false);
    }
    fetchData();
    includeFunctionHere();

  }, [])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM