【问题标题】:JSX skip if JSON field does not exist如果 JSON 字段不存在,则 JSX 跳过
【发布时间】:2016-05-27 09:34:35
【问题描述】:

我目前正在处理来自 API 的 JSON 文件,如果字段为空,该文件不会添加密钥对。在尝试遍历整个 JSON 文件时,这让我很伤心。

我的代码目前是

var ListOfItems = React.createClass({
    render: function () {
        var itemList = jsonFile.data.map(function(item)
        {
            return <Item key={item.__key}
                itemQuestion={item.question}
                itemQuestionAnswer={item.answer.answer}
                userName={item.user.name}
                staffName={item.staff.name}
                staffImage={item.staff.image_url} />
        });

        return (
            <div>
            <ul>{itemList}</ul>
            </div>
        );
    }
});

当 item.answer.answer 没有价值时会报错。

任何帮助将不胜感激。

【问题讨论】:

    标签: javascript reactjs react-jsx jsx


    【解决方案1】:

    您可以通过添加条件来检查项目的答案类型是否不是undefined。如果不是,则继续返回一个值,否则不返回任何内容。这样,您只有在条件已通过时才附加另一个项目(我使用了该条件的简写形式)。

    var ListOfItems = React.createClass({
        render: function() {
            var itemList = jsonFile.data.map(function(item)
            {
                typoeof item.answer != 'undefined' && 
                return <Item  key={item.__key} itemQuestion={item.question}
                    itemQuestionAnswer={item.answer.answer} userName={item.user.name}
                    staffName={item.staff.name} staffImage={item.staff.image_url} />
            });
    
            return (
                <div>
                    <ul>{itemList}</ul>
                </div>
            );
        }
    });
    

    如果您总是得到item.answer,但它的answerundefinednull,您可以在我提供的代码中检查item.answer.answer

    【讨论】:

    • 我很惊讶没有更简单的解决方案。在构建视图时,有一种简单的方法来遍历长对象路径并默默地忽略任何丢失的字段是非常方便的。
    【解决方案2】:

    根据您的项目列表有多大,您可以使用builtin filter Array method 首先删除所有您不想要的项目,然后继续映射它们。请记住,这可能会遍历您的整个列表两次。

    关于从map 内部返回undefined 的说明。这将不会阻止商品被退回。相反,您的结果数组中将有一个 undefined 项目。数组将不会变短。

    这是filter() 的示例:

    var ListOfItems = React.createClass({
      renderItems: function() {
        return jsonFile.data
          .filter(function(item) {
            // This will return any item that has a truthy answer
            return item.answer && item.answer.answer;
          })
          .map(function(item) {
            return (
              <Item
                key={item.__key}
                itemQuestion={item.question}
                itemQuestionAnswer={item.answer.answer}
                userName={item.user.name}
                staffName={item.staff.name}
                staffImage={item.staff.image_url} />
            );
          });
      },
    
      render: function() {
        return (
          <div>
            <ul>
              {this.renderItems()}
            </ul>
          </div>
        );
      }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-09
      • 2015-12-02
      • 2018-07-22
      • 1970-01-01
      • 1970-01-01
      • 2022-07-16
      • 2013-07-18
      相关资源
      最近更新 更多