为什么这不会在屏幕上显示任何内容 - 关于唯一关键道具的警告(React Native)



我正在创建一个应用程序并尝试组件,最重要的是动画。 我有以下代码,其中包含两个类组件:

import * as React from 'react';
import { StyleSheet, Text, View,  TouchableOpacity, Image, ImageBackground, Animated, Easing, Platform
} from 'react-native';
import { frame1 } from '../master-new/assets/index';
import { frame2 } from '../master-new/assets/index';
import { frame3 } from '../master-new/assets/index';
import { background } from '../master-new/assets/index';
const Images= [
{ id: 1, src: frame1, title: 'foo', description: 'bar'},
{ id: 2, src: frame2, title: 'foo', description: 'bar'},
]
const length = Images.length;
class Animation extends React.Component {
constructor(){
super();
this.animations = new Animated.Value(0);
this.opacity = [];
Images.map((item, index) => {
this.opacity.push(
this.animations.interpolate({
inputRange: [index - 1, index, index + 1],
outputRange: [0, 1, 0],
}),
);
});
}
componentDidMount() {
Animated.loop(
Animated.timing(this.animations, {
toValue: length - 1,
duration: 2000 * length,
easing: Easing.linear,
useNativeDriver: true,
}),
).start();
}
render() {
return(
<View style={styles.container}>
{Images.map((item, index) => {
const opacity = this.opacity[index];
return (
<Animated.View
style={[styles.anim, {frame: item, opacity}]}
/>
);
})}
</View>
)
}
}
export default class Timer extends React.Component {
constructor(props){
super(props);
this.state = {
time:0,
start:0,
isOn:false, 
submit:false,
scoreArray: [],
animalArray: [],
fadeAnim: new Animated.Value(0),
pauseOver: false,
pauseToggle: 'up',
}
}
sampleInfo = [
{
second: 1,
ml: '19ml',
animal: 'Thing1',
weight: '4kg',
capacity: '20ml'
},
{
second: 2,
ml: '38ml',
animal: 'Thing2',
weight: '7kg',
capacity: '35ml'
},
{
second: 3,
ml: '57ml',
animal: 'Thing3',
weight: '12kg',
capacity: '60ml'
}
] 
render() {
return(
<View style={styles.container}>
<Animation />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: "column"
},
background: {
flex: 1,
resizeMode: "cover",
justifyContent: "center"
},
anim: {
flex: 1,
width: '100%'
}
});

我正在使用 expo 显示,并且之前已成功显示应用程序并在实际中对其进行了测试。有人可以告诉我为什么我只看到这个空白屏幕吗?

我收到一条警告,说列表中的每个智利都应该有一个唯一的键道具。检查动画的渲染方法,所以我想这就是问题所在,但为什么以及它只是白屏的原因吗?

我读过:警告:数组或迭代器中的每个孩子都应该有一个唯一的"键"道具。检查"列表视图"的呈现方法

和:

https://reactjs.org/docs/lists-and-keys.html

但它并没有为我澄清任何事情!

T

react 需要一种方法来识别 UI 内的节点,当您渲染列表/数组时,您需要为组件提供key属性,在您的情况下是当您渲染图像数组时,也就是 react 抱怨这一点时,react 需要这个来知道如果状态更新要更新什么项目。

要解决此问题,只需将key属性添加到组件中,确保值是唯一的,可以是项的 ID 或索引


render() {
return(
<View style={styles.container}>
{Images.map((item, index) => {
const opacity = this.opacity[index];
return (
<Animated.View
key = {item.id}
style={[styles.anim, {frame: item, opacity}]}
/>
);
})}
</View>
)
}

附注: 仅使用索引作为最后的手段,在您的情况下,您有 ID,保证是唯一的,但不能保证索引。

您需要将key属性放在循环中返回的 JSX 元素上。喜欢:

{Images.map((item, index) => {
const opacity = this.opacity[index];
return (
<Animated.View
key={index}
style={[styles.anim, {frame: item, opacity}]}
/>
);
})}

最新更新