簡體   English   中英

為什么反應文本組件不顯示對我的數組 state 的更新

[英]Why is the react text component not displaying updates to my array state

我正在嘗試熟悉 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 顯示 state 正在更改,但實際應用程序內的文本組件中顯示的內容永遠不會更新。 然后我使用單獨的 integer 狀態嘗試了這個,如下所示:

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

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

使用 integer state (如上述)完全可以按預期工作。 誰能告訴我我的陣列 state 做錯了什么? 謝謝你。

您的代碼看起來很完美,應該可以正常工作。

這是稍微修改的示例,其中第一個元素是隨機生成的,並且在Text組件中正確顯示。

工作示例: Expo 小吃

在此處輸入圖像描述

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',
  },
});

您的代碼看起來不錯,我按照您的代碼嘗試了以下操作,可以看到 state 和 UI 在單擊按鈕時成功更新。

您能否檢查一下您的事件處理程序 function 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>
   );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM