简体   繁体   English

在 react-native 中一致地向数组添加元素

[英]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.今天我想在 react-native 中创建数组并通过钩子更新它以按顺序在屏幕上显示元素。 So the final result should be 0 1 2 3 4 My code so far所以最终结果应该是0 1 2 3 4我的代码到目前为止

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 .但这仅向我显示了数组的最后一个元素,即4 How can i display all elements in sequence on the screen?如何在屏幕上按顺序显示所有元素?

React state update is async. React 状态更新是异步的。 On surface it looks like you are updating state 5 times.从表面上看,您似乎正在更新状态 5 次。 but the state is being updated only once and when it get's update i value is already 4.但是状态只更新一次,当它得到更新时, i值已经是 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为了不出现性能问题,react 还会在重新渲染(和更新状态)之前等待函数调用结束,因此在 for 循环中,始终将带有当前索引的空数组传递到状态

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

will give you the current value here会给你这里的当前值

You need iterate array with Array#map您需要使用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.并且在 map 之后而不是在循环内更好地调用setArr 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);
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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