简体   繁体   中英

Add elements to array consistently in react-native

Today i want to create array in react-native and update it via hook to display elements on the screen in sequence. So the final result should be 0 1 2 3 4 My code so far

import React, { useState, useRef } from "react";
import { StyleSheet, Text, View, Button } from "react-native";

export default function App() {
  const [arr, setArr] = useState([]);
  function test() {
    for (var i = 0; i < 5; i++) {
      setArr([...arr, i]);
    }
  }

  return (
    <View style={styles.container}>
      <Text>{arr}</Text>
      <Button title="change next index" onPress={() => test()} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center",
  },
});

But this shows me only the last elements of the array which is 4 . How can i display all elements in sequence on the screen?

React state update is async. On surface it looks like you are updating state 5 times. but the state is being updated only once and when it get's update i value is already 4.

function test() {
  for (let i = 0; i < 5; i++) {
    setArr(prevState => [...prevState, i]);
  }
}

You need to join all elements of the array

return (
  <View style={styles.container}>
    <Text>{arr.join(' ')}</Text>
    <Button title="change next index" onPress={() => test()} />
  </View>
);

or if you want to wrap each number in an own element

return (
  <View style={styles.container}>
    {
      arr.map(num => (<Text key={num}>{num}</Text>))
    }
    <Button title="change next index" onPress={() => test()} />
  </View>
);

To not have performance issues, react also waits for the end of a function call before re-rendering (and update states), so in your for loop, you always pass an empty array with the current index into the state

setArr(prev=> [...prev, i]);

will give you the current value here

You need iterate array with Array#map

Codesandbox Demo

 <View style={styles.container}>
      {arr && arr.map(a=>(<Text key={a}>{a}</Text>))}
      <Button title="change next index" onPress={() => test()} />
 </View>

And also better setArr call on after map instead of inside the loop. Check my demo link . Because each time call unnecessary render on the loop

function test() {
    let newArr = [...arr];
    for (var i = 0; i < 5; i++) {
      newArr.push(i);
    }
    setArr(newArr);
  }

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