【问题标题】:Why is the react text component not displaying updates to my array state为什么反应文本组件不显示对我的数组状态的更新
【发布时间】:2021-05-09 11:13:20
【问题描述】:

我正在尝试熟悉 React Native。目前我正在开发一个应用程序,但在尝试显示对数组的各个元素的更改时遇到了一个问题。例如:

function MyApp() {
    const [array, setArray] = useState([1,2,3]);

    const onPress = () => {
        let temp = [3,2,1];
        setArray(temp);
    }
    
    return(
        <View>
            <TouchableHighlight onPress={onPress}> 
                 <View>
                     <Text>{array[0]}</Text>
                 </View>
            </TouchableHighlight>
        </View>
    );
}

使用上面的代码,我希望在文本组件中显示“1”,并在按下时变为“3”。 console.log 显示正在更改的状态,但实际应用程序内的文本组件中显示的内容永远不会更新。然后我尝试使用单个整数状态,如下所示:

const [int, setInt] = useState(0);

const onPress = () => {
    setInt(1);
}

使用像上面这样的整数状态完全可以按预期工作。谁能告诉我我的数组状态做错了什么?谢谢。

【问题讨论】:

标签: javascript arrays reactjs react-native setstate


【解决方案1】:

您的代码看起来很完美,应该可以正常运行。

这是稍微修改的示例,其中第一个元素是随机生成的,并且在Text 组件中正确显示。

工作示例:Expo Snack

import React, { useState } from 'react';
import { Text, View, StyleSheet, TouchableHighlight } from 'react-native';
import Constants from 'expo-constants';

export default function MyApp() {
  const [array, setArray] = useState([1, 2, 3]);

  const onPress = () => {
    let temp = [Math.floor(Math.random() * 10), 2, 1];
    setArray(temp);
  };

  return (
    <View style={styles.container}>
      <TouchableHighlight onPress={onPress}>
        <View style={styles.btn}>
          <Text
            style={{ alignSelf: 'center', fontSize: 28, fontWeight: 'bold' }}>
            {array[0]}
          </Text>
        </View>
      </TouchableHighlight>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  btn: {
    width: 100,
    height: 100,
    borderColor: 'purple',
    borderWidth: 5,
    justifyContent: 'center',
  },
});

【讨论】:

    【解决方案2】:

    您的代码看起来没问题,我按照您的代码尝试了以下操作,可以看到在单击按钮时状态和 UI 已成功更新。

    您能否检查一下您的事件处理函数 onPress 是否被调用,以及当您单击它时控制台中是否出现任何错误。

    function App() {
      const [array, setArray] = React.useState([1, 2, 3]);
    
      const handleBtnClick = () => {
        const temp = [3, 2, 1];
        setArray(temp);
      };
    
      return (
        <React.Fragment>
          <button onClick={handleBtnClick}>Click</button>
          {array.map((el) => (
            <p>{el}</p>
          ))}
          <hr />
          {array[0]}
        </React.Fragment>
       );
    }
    

    【讨论】:

      猜你喜欢
      • 2021-04-28
      • 2020-06-16
      • 1970-01-01
      • 2016-01-19
      • 2019-07-16
      • 2020-03-29
      • 1970-01-01
      • 1970-01-01
      • 2021-10-22
      相关资源
      最近更新 更多