Home > database >  I want to call a function before going through map function
I want to call a function before going through map function

Time:10-01

I want to call a function each time I want to render a part of page.

This is my code

 random() (
          randomNumbers && (
            randomNumbers.map((item,i) => (
               <div>{item}</div>
            )

I want first to execute the random funciton then loop through that. The reason why I'm not doing this when page is rendered because I need to call this several times

Thanks a lot.

CodePudding user response:

Maybe set random number elements as property of your class:

randomNumbers = this.random()

render() {
  return (
this.randomNumbers 
)
  
}

Since it's already an array, you won't have to loop it, just return it

CodePudding user response:

Im not 100% sure what it is you want to do with this, but I think this is what you want.

https://codesandbox.io/s/heuristic-nightingale-v1j03?file=/src/App.tsx:0-495

import "./styles.css";
import { useState, useEffect } from "react";

function generateRandomNumbers(len: number): number[] {
  return new Array(len).fill(undefined).map((_) => Math.random());
}

export default function App() {
  const [rNums, setRNums] = useState<number[]>([]);

  useEffect(() => setRNums(generateRandomNumbers(5)), []); // [0.12, 0.96, 0.4, 0.5, 0.2]

  return (
    <div className="App">
      {rNums.map((num) => (
        <p key={num}>{num}</p>
      ))}
    </div>
  );
}


  • Related