在更新状态数组后不重新渲染本机

问题描述 投票:0回答:1

我有以下代码(完整示例):

import React, { useState, useEffect } from 'react';
import { SafeAreaView, View, Button, StyleSheet, Animated } from 'react-native';
import { PanGestureHandler, State } from 'react-native-gesture-handler';

const App = () => {

  const [blocks, setBlocks] = useState([]);

  const CreateBlockHandler = () => {
    let array = blocks;
    array.push({
      x: new Animated.Value(0),
      y: new Animated.Value(0)
    });
    setBlocks(array);
    RenderBlocks();
  };

  const MoveBlockHandler = (index, event) => {
    Animated.spring(blocks[index].x, { toValue: event.nativeEvent.x }).start();
    Animated.spring(blocks[index].y, { toValue: event.nativeEvent.y }).start();
  };

  const RenderBlocks = () => {
      return blocks.map((item, index) => {
        return (
          <PanGestureHandler key={index} onGestureEvent={event => MoveBlockHandler(index,event)}>
            <Animated.View style={[styles.block, {
              transform: [
                { translateX: item.x },
                { translateY: item.y }
              ]
            }]} />
          </PanGestureHandler>
        )
      });
  };


  return (

    <SafeAreaView style={styles.container}>
      <View style={styles.pancontainer}>
        <RenderBlocks />
      </View>
      <Button title="Add block" onPress={CreateBlockHandler} />
    </SafeAreaView>

  );

};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center'
  },
  pancontainer: {
    width: '95%',
    height:'75%',
    borderWidth: 1,
    borderColor: 'black'
  },
  block: {
    width: 50,
    height: 50,
    backgroundColor: 'black'
  }
});

export default App;

此代码做什么?这是一个大正方形,下面有一个按钮。当我单击按钮时,将在大方块中创建一个新的黑色方块(50x50)。我通过创建一个新的数组元素(array =块)来做到这一点。这是在功能CreateBlockHandler中完成的。这不能正常工作!

函数MoveBlockHandler使小方块可移动。这有效!

什么不起作用?当我创建一个新的黑色正方形时,该黑色正方形不会显示在屏幕上。只有当我刷新时,正方形才会呈现。这个正方形是通过CreateBlockHandler创建的,因为当我在该函数中执行console.log(blocks)时,我可以看到添加了一个新的数组元素。

我如何强制此代码对所有数组元素进行完全重新渲染?我试图将正方形的渲染包装在单独的函数中(RenderBlocks),并且每次创建新正方形时都会调用此函数(CreateBlockHandler中的最后一行)。该函数被调用(我可以使用console.log()进行检查),但是没有渲染正方形。

reactjs react-native
1个回答
0
投票
 const CreateBlockHandler = () => {
    let array = [...blocks];
    array.push({
      x: new Animated.Value(0),
      y: new Animated.Value(0)
    });
    setBlocks(array);
    RenderBlocks
© www.soinside.com 2019 - 2024. All rights reserved.