[英]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.