为了账号安全,请及时绑定邮箱和手机立即绑定

RN - 直接从状态语法映射

RN - 直接从状态语法映射

幕布斯7119047 2022-12-02 17:24:27
我正在尝试从状态映射一个数组 - 但对正确的语法感到困惑 - 谁能告诉我哪里出错了:这是我在莫:      newsStorys = () => {    return (      {this.state.newsFeed.map((a) => {        <View style={ModalStyles.newsArticle}>          <Text style={ModalStyles.newsDate}>{a.date}</Text>          <Text style={ModalStyles.newsTitle}>{a.title}</Text>          <Text style={ModalStyles.newsDesc}>          {a.story}          </Text>        </View>    }  }    );  };
查看完整描述

3 回答

?
斯蒂芬大帝

TA贡献1827条经验 获得超8个赞

我不确定这是否是您组件的全部代码,但我可以看到三件事。

  1. 如果newsFeed在组件首次渲染时未初始化(假设它尚未定义),newsFeed.map()则将抛出异常。

  2. 您不会从地图调用中返回任何内容。你应该这样写:

   newsStorys = () => {

      if (!this.state.newsFeed) return null;

      return this.state.newsFeed.map((a) => ({ // <--- note the parentheses here, you don't have it

          <View style={ModalStyles.newsArticle}>

            <Text style={ModalStyles.newsDate}>{a.date}</Text>

            <Text style={ModalStyles.newsTitle}>{a.title}</Text>

            <Text style={ModalStyles.newsDesc}>

              {a.story}

            </Text>

          </View>

       });

     );

   };

如果你想避免括号,那么你需要明确地返回一些东西,就像这样:


    this.state.newsFeed.map((a) => {

       return (

          <View style={ModalStyles.newsArticle}>

            <Text style={ModalStyles.newsDate}>{a.date}</Text>

            <Text style={ModalStyles.newsTitle}>{a.title}</Text>

            <Text style={ModalStyles.newsDesc}>

              {a.story}

            </Text>

          </View>

       );

    });

您可能需要一个额外的视图来包装 map 返回的视图列表。


您还需要为每个视图提供一个唯一的键,以便 React 可以跟踪它们。

   <View style={ModalStyles.newsArticle} key={'nome unique value'}>

     ...

   </View>


最后我认为使用 aFlatList而不是map.


干杯!


查看完整回答
反对 回复 2022-12-02
?
尚方宝剑之说

TA贡献1788条经验 获得超4个赞

在网上玩了一圈,并进行了很好的挖掘,找到了语法答案:(感谢 Bruno 提供的关键和指针)。


newsStorys = () => {

   

    return this.state.newsFeed.map((value, index) => {

      return (

        <View style={ModalStyles.newsArticle} key={index}>

          <Text style={ModalStyles.newsDate}>{value.date}</Text>

          <Text style={ModalStyles.newsTitle}>{value.title}</Text>

          <Text style={ModalStyles.newsDesc}>{value.story}</Text>

        </View>

      );

    });

  };


查看完整回答
反对 回复 2022-12-02
?
守着一只汪

TA贡献1872条经验 获得超3个赞

尝试这个


newsStorys = () => (

    this.state.newsFeed.map(({ date, story, title }, index) =>

        <View key={`news-${index}`} style={ModalStyles.newsArticle}>

            <Text style={ModalStyles.newsDate}>{date}</Text>

            <Text style={ModalStyles.newsTitle}>{title}</Text>

            <Text style={ModalStyles.newsDesc}>{story}</Text>

        </View>

    ));


查看完整回答
反对 回复 2022-12-02
  • 3 回答
  • 0 关注
  • 78 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信