简体   繁体   中英

How to Add current i's value of for loop into an empty array state in react functional component?

    const [btn, setBtn] = useState([]);
    let newArray = []
    for (let i = 1; i<=10; i++) {
      newArray.push(i);
      console.log(btn);
      setBtn([...btn,...newArray])
    }
  • i have tried to add newArray to state by using the spred operatar but this will result into an infinite loop and my react app is crashed and after geeting the 1 to 10 value in my btn array i need to use loop over my btn array state.*

put it inside useEffect

const [btn, setBtn] = useState([]);

useEffect(() => { 
    const newArray = []
    for (let i = 1; i<=10; i++) {
      newArray.push(i); 
      setBtn([...btn,...newArray]) 
    }
}, [])

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