【问题标题】:React Native Mapping Fail反应本机映射失败
【发布时间】:2018-02-13 03:47:43
【问题描述】:

在这里反应新手。我有一些 React 代码,我试图循环遍历我在 .state 中提供的数组并显示图像。 (使用 'Image' 并使用来自 https://github.com/lhandel/react-native-card-stack-swiper 的 Card 对象来显示 Card 对象内的 Image,它本身嵌套在 Object 中,但这既不是这里也不是那里。)

export default class App extends Component<{}> {
  constructor(props) {
    super(props);
    this.state = {
      cards: [
        {itemname: 'Item 1',
          restoname: 'Resto 1',
          url: 'https://res.cloudinary.com/grubhub/image/upload/v1515191165/bkf4niv9okipbc8y6o8h.jpg',
          description: 'Desc 1'},
        {itemname: 'Item 2',
          restoname: 'Resto 2',
          url: 'https://res.cloudinary.com/grubhub/image/upload/v1514060352/twhriy3hvbzayktrjp91.jpg',
          description: 'Desc 2'}
      ]
    };
  }

render() {
    const contents = this.state.cards.map((item, index) => {
      return (
          <Card key={'Card_' + index}>
            <Image
                key={index}
                source={{uri: item.url}} />
          </Card>
      )
    });

return (
      <View style={{flex:1}}>

        <CardStack
          cards = {this.state.cards}
        >

         <View>
            {contents}
         </View>
        </CardStack>

我的不足之处是最后一部分 --- 如果我将内容定义为在其中返回 &lt;Card&gt;&lt;Image&gt; 对象的映射,那么它不应该在最后出现我在&lt;CardStack&gt; 对象内调用{contents}?什么都没有显示,也没有错误消息。

另外,除了最初什么都没有显示之外,如果我滑动到下一张卡片,我会收到以下错误:

undefined 不是对象(评估 'this.state.cards[sindex - 2].props`)

【问题讨论】:

  • 啊,想通了,我不需要 对象。可能不是很好的 JSX,但仅将 {contents} 单独放置似乎就足够了。

标签: javascript reactjs react-native mapping


【解决方案1】:

将密钥分配给卡片而不是图像,如下所示:

return (
   <Card key={index}>
       <Image
          source={{uri: item.url}} />
   </Card>
)

动态创建元素时,包装元素需要密钥,在这种情况下,该元素是卡片。

另外,根据DOC,您需要将 Card 元素直接放在 CardStack 中,所以删除视图并这样写:

<CardStack> {contents} </CardStack>

【讨论】:

  • 感谢 Mayank - 但即使进行了更改,我仍然没有显示任何内容。另外,正如我所补充的,如果我滑动到下一张卡片,我会得到一个error of undefined is not an object (evaluating 'this.state.cards[sindex - 2].props) ——知道这意味着什么吗?
  • trythis:&lt;CardStack&gt; {contents} &lt;/CardStack&gt; 移除卡片组内的视图。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-14
  • 2019-08-01
  • 2020-08-10
  • 1970-01-01
  • 2019-03-19
  • 2022-08-16
相关资源
最近更新 更多