【发布时间】:2019-04-24 11:56:03
【问题描述】:
我正在尝试以卡片的形式呈现数据数组。但是,一次只能将一个项目呈现为单张卡片。用户更新卡号后,将呈现下一项。 我无法在渲染函数中明智地调用数组项。
列表的映射函数对我不起作用,因为它会填充整个数组,但我希望用户在下一个项目之前输入。
此数据是通过 API 调用保存的
data = [
{ id: 1, text: 'Card #1', uri: 'https://images.unsplash.com/photo-1535591273668-578e31182c4f?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=f28261f0564880c9086a57ee87a68887&auto=format&fit=crop&w=500&q=60' },
{ id: 2, text: 'Card #2', uri: 'https://images.unsplash.com/photo-1535576434247-e0f50b766399?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=232f6dbab45b3f3a6f97e638c27fded2&auto=format&fit=crop&w=500&q=60' },
{ id: 3, text: 'Card #3', uri: 'https://images.unsplash.com/photo-1535565454739-863432ea3c0e?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=7edfb9bc7d214dbf2c920723cb0ffce2&auto=format&fit=crop&w=500&q=60' },
];
这是数据数组。现在来自渲染函数:
renderCard() {
const buttons = ['Call', 'Fold', 'Raise']
const selectedIndex = this.state.selectedIndex
return (
<Card
title="Profiling Question "
image={{ uri: this.state.data[selectedIndex].uri }}
>
<Text style={{ marginBottom: 10 }}>
{this.state.data[selectedIndex].text}
</Text>
<Button
onPress={this.updateIndex}
/>
</Card>
);
}
UpdateIndex 函数更新索引值。这工作正常。
我希望使用按钮呈现单张卡片以更新到下一张卡片。
但是我收到了这个错误:
TypeError: undefined is not an object(evaluting'this.state.data[selectedIndex].uri')
编辑:
我也试过删除索引来检查如下:
return (
<Card
title={"Question No: "+ this.state.selectedIndex +1 }
image={{ uri: this.state.data[0].question_image }}
>
<Text style={{ marginBottom: 10 }}>
{this.state.data[0].question_text}
</Text>
<Button
onPress={this.updateLn}>
<Text> Update Question </Text>
</Button>
</Card>
);
还是一样的错误。
我的状态是:
export default class QuizScreen extends Component {
constructor(props) {
super(props)
this.state = {
data: [],
selectedIndex: 0,
dataLength: 0,
cardIndex: 0,
};
this.updateIndex = this.updateIndex.bind(this)
this.updateLn = this.updateLn.bind(this)
}```
【问题讨论】:
-
你能显示预期结果的截图吗?
-
const { selectedIndex } = this.state?? -
您在 const 中设置数组数据并尝试从状态中获取。重新检查您的代码一次
-
抱歉复制中的错别字。再次编辑有问题的代码。
-
移除渲染卡中的状态
标签: arrays reactjs react-native